diff --git a/install/recoverFilesToVideos.php b/install/recoverFilesToVideos.php index 411fdf53e..2c12a1b28 100644 --- a/install/recoverFilesToVideos.php +++ b/install/recoverFilesToVideos.php @@ -1,73 +1,73 @@ $value) { $video = Video::getVideoFromFileName($value[0], true); if (!empty($video)) { unset($files[$key]); } } echo "*** Total filenames " . $total . " Will be created\n"; echo "*** Confirm Create Them? y/n: "; ob_flush(); $confirm = trim(readline("")); if (!empty($confirm) && strtolower($confirm) === 'y') { $count = 0; foreach ($files as $key => $value) { $count++; $title = "Video recovered: ".date("Y-m-d H:i:s", filectime($value[1])); $video = new Video($title, $value[0]); - $video->setStatus('a'); + $video->setStatus(Video::$statusActive); $video->setUsers_id(1); if($video->save(false, true)){ echo "{$count}/{$total} {$title} created\n"; }else{ echo "{$count}/{$total} ERROR on create video {$title}\n"; } } } \ No newline at end of file diff --git a/objects/Object.php b/objects/Object.php index 064e756fa..15b8a9372 100644 --- a/objects/Object.php +++ b/objects/Object.php @@ -1,649 +1,654 @@ load($id); } } protected function load($id) { $row = self::getFromDb($id); if (empty($row)) { return false; } foreach ($row as $key => $value) { $this->$key = $value; } return true; } public static function getNowFromDB() { global $global; $sql = "SELECT NOW() as my_date_field"; $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } return $row; } public static function setTimeZone() { global $advancedCustom; $row = self::getNowFromDB(); $dt = new DateTime($row['my_date_field']); - $timeZOnesOptions = object_to_array($advancedCustom->timeZone->type); - if (empty($timeZOnesOptions[$advancedCustom->timeZone->value])) { + if(!empty($_COOKIE['timezone'])){ + $timezone = $_COOKIE['timezone']; + }else{ + $timeZOnesOptions = object_to_array($advancedCustom->timeZone->type); + $timezone = $timeZOnesOptions[$advancedCustom->timeZone->value]; + } + if (empty($timezone)) { return false; } try { - $objDate = new DateTimeZone($timeZOnesOptions[$advancedCustom->timeZone->value]); + $objDate = new DateTimeZone($timezone); if (is_object($objDate)) { $dt->setTimezone($objDate); - date_default_timezone_set($timeZOnesOptions[$advancedCustom->timeZone->value]); + date_default_timezone_set($timezone); return $dt; } return false; } catch (Exception $exc) { _error_log("setTimeZone: " . $exc->getMessage(), AVideoLog::$ERROR); return false; } } protected static function getFromDb($id) { global $global; $id = intval($id); $sql = "SELECT * FROM " . static::getTableName() . " WHERE id = ? LIMIT 1"; // I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about $res = sqlDAL::readSql($sql, "i", array($id), true); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } return $row; } public static function getAll() { global $global; if (!static::isTableInstalled()) { return false; } $sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } public static function getAllActive() { global $global; if (!static::isTableInstalled()) { return false; } $sql = "SELECT * FROM " . static::getTableName() . " WHERE status='a' "; $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } public static function getTotal() { //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; if (!static::isTableInstalled()) { return 0; } $sql = "SELECT id FROM " . static::getTableName() . " WHERE 1=1 "; $sql .= self::getSqlSearchFromPost(); $res = sqlDAL::readSql($sql); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); return $countRow; } public static function getSqlFromPost($keyPrefix = "") { global $global; $sql = self::getSqlSearchFromPost(); if (empty($_POST['sort']) && !empty($_GET['order'][0]['dir'])) { $index = intval($_GET['order'][0]['column']); $_GET['columns'][$index]['data']; $_POST['sort'][$_GET['columns'][$index]['data']] = $_GET['order'][0]['dir']; } // add a security here if (!empty($_POST['sort'])) { foreach ($_POST['sort'] as $key => $value) { $_POST['sort'][xss_esc($key)] = xss_esc($value); } } if (!empty($_POST['sort'])) { $orderBy = array(); foreach ($_POST['sort'] as $key => $value) { $key = $global['mysqli']->real_escape_string($key); //$value = $global['mysqli']->real_escape_string($value); $direction = "ASC"; if (strtoupper($value) === "DESC") { $direction = "DESC"; } $key = preg_replace("/[^A-Za-z0-9._ ]/", '', $key); $orderBy[] = " {$keyPrefix}{$key} {$value} "; } $sql .= " ORDER BY " . implode(",", $orderBy); } $sql .= self::getSqlLimit(); return $sql; } public static function getSqlLimit() { global $global; $sql = ""; if (empty($_POST['rowCount']) && !empty($_GET['length'])) { $_POST['rowCount'] = intval($_GET['length']); } if (empty($_POST['current']) && !empty($_GET['start'])) { $_POST['current'] = ($_GET['start'] / $_GET['length']) + 1; } elseif (empty($_POST['current']) && isset($_GET['start'])) { $_POST['current'] = 1; } $_POST['current'] = getCurrentPage(); $_POST['rowCount'] = getRowCount(); if (!empty($_POST['rowCount']) && !empty($_POST['current']) && $_POST['rowCount'] > 0) { $_POST['rowCount'] = intval($_POST['rowCount']); $_POST['current'] = intval($_POST['current']); $current = ($_POST['current'] - 1) * $_POST['rowCount']; $current = $current < 0 ? 0 : $current; $sql .= " LIMIT $current, {$_POST['rowCount']} "; } else { $_POST['current'] = 0; $_POST['rowCount'] = 0; $sql .= " LIMIT 1000 "; } return $sql; } public static function getSqlSearchFromPost() { $sql = ""; if (!empty($_POST['searchPhrase'])) { $_GET['q'] = $_POST['searchPhrase']; } elseif (!empty($_GET['search']['value'])) { $_GET['q'] = $_GET['search']['value']; } if (!empty($_GET['q'])) { global $global; $search = $global['mysqli']->real_escape_string(xss_esc($_GET['q'])); $like = array(); $searchFields = static::getSearchFieldsNames(); foreach ($searchFields as $value) { $like[] = " {$value} LIKE '%{$search}%' "; // for accent insensitive $like[] = " CONVERT(CAST({$value} as BINARY) USING utf8) LIKE '%{$search}%' "; } if (!empty($like)) { $sql .= " AND (" . implode(" OR ", $like) . ")"; } else { $sql .= " AND 1=1 "; } } return $sql; } public function save() { if (!$this->tableExists()) { _error_log("Save error, table " . static::getTableName() . " does not exists", AVideoLog::$ERROR); return false; } global $global; $fieldsName = $this->getAllFields(); if (!empty($this->id)) { $sql = "UPDATE " . static::getTableName() . " SET "; $fields = array(); foreach ($fieldsName as $value) { if (strtolower($value) == 'created') { // do nothing } elseif (strtolower($value) == 'modified') { $fields[] = " {$value} = now() "; } elseif (is_numeric($this->$value)) { $fields[] = " `{$value}` = {$this->$value} "; } elseif (strtolower($this->$value) == 'null') { $fields[] = " `{$value}` = NULL "; } else { $fields[] = " `{$value}` = '{$this->$value}' "; } } $sql .= implode(", ", $fields); $sql .= " WHERE id = {$this->id}"; } else { $sql = "INSERT INTO " . static::getTableName() . " ( "; $sql .= "`" . implode("`,`", $fieldsName) . "` )"; $fields = array(); foreach ($fieldsName as $value) { if (strtolower($value) == 'created' || strtolower($value) == 'modified') { $fields[] = " now() "; } elseif (!isset($this->$value) || strtolower($this->$value) == 'null') { $fields[] = " NULL "; } else { $fields[] = " '{$this->$value}' "; } } $sql .= " VALUES (" . implode(", ", $fields) . ")"; } //if(static::getTableName() == 'subscriptions') echo $sql; $insert_row = sqlDAL::writeSql($sql); if ($insert_row) { if (empty($this->id)) { $id = $global['mysqli']->insert_id; } else { $id = $this->id; } return $id; } else { _error_log("ObjectYPT::save Error on save: " . $sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error, AVideoLog::$ERROR); return false; } } private function getAllFields() { global $global, $mysqlDatabase; $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = '" . static::getTableName() . "'"; $res = sqlDAL::readSql($sql, "s", array($mysqlDatabase)); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row["COLUMN_NAME"]; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } public function delete() { global $global; if (!empty($this->id)) { $sql = "DELETE FROM " . static::getTableName() . " "; $sql .= " WHERE id = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($this->id)); } _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); return false; } public static function setCache($name, $value) { $cachefile = self::getCacheFileName($name); make_path($cachefile); $content = _json_encode($value); if(empty($content)){ $content = $value; } $bytes = @file_put_contents($cachefile, $content); self::setSessionCache($name, $value); return array('bytes' => $bytes, 'cachefile' => $cachefile); } public static function cleanCacheName($name) { $name = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $name); $name = preg_replace('/[!#$&\'()*+,:;=?@[\\]% -]+/', '_', trim(strtolower(cleanString($name)))); $name = preg_replace('/\/{2,}/', '/', trim(strtolower(cleanString($name)))); if (function_exists('mb_ereg_replace')) { $name = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).\\/\\\])", '', $name); // Remove any runs of periods (thanks falstro!) $name = mb_ereg_replace("([\.]{2,})", '', $name); } return preg_replace('/[\x00-\x1F\x7F]/u', '', $name); } /** * * @param type $name * @param type $lifetime, if is = 0 it is unlimited * @return type */ public static function getCache($name, $lifetime = 60, $ignoreSessionCache = false) { if (isCommandLineInterface()) { return false; } global $getCachesProcessed, $_getCache; if (empty($_getCache)) { $_getCache = array(); } if (empty($getCachesProcessed)) { $getCachesProcessed = array(); } $cachefile = self::getCacheFileName($name); if (!empty($_getCache[$name])) { return $_getCache[$name]; } if (empty($getCachesProcessed[$name])) { $getCachesProcessed[$name] = 0; } $getCachesProcessed[$name]++; if (!empty($_GET['lifetime'])) { $lifetime = intval($_GET['lifetime']); } if (empty($ignoreSessionCache)) { $session = self::getSessionCache($name, $lifetime); if (!empty($session)) { $_getCache[$name] = $session; return $session; } } /* if (preg_match('/firstpage/i', $cachefile)) { echo var_dump($cachefile) . PHP_EOL; $trace = debug_backtrace(); $backtrace_lite = array(); foreach ($trace as $call) { echo $call['function'] . " " . $call['file'] . " line " . $call['line'] . PHP_EOL; }exit; } /** */ if (file_exists($cachefile) && (empty($lifetime) || time() - $lifetime <= filemtime($cachefile))) { //if(preg_match('/getStats/', $cachefile)){echo $cachefile,'
';} $c = @url_get_contents($cachefile); $json = _json_decode($c); if(empty($json) && !is_object($json) && !is_array($json)){ $json = $c; } self::setSessionCache($name, $json); $_getCache[$name] = $json; return $json; } elseif (file_exists($cachefile)) { self::deleteCache($name); } return null; } public static function deleteCache($name) { global $__getAVideoCache; unset($__getAVideoCache); $cachefile = self::getCacheFileName($name); @unlink($cachefile); self::deleteSessionCache($name); ObjectYPT::deleteCacheFromPattern($name); } static function deleteCachePattern($pattern) { global $__getAVideoCache; unset($__getAVideoCache); $tmpDir = self::getCacheDir(); $array = _glob($tmpDir, $pattern); foreach ($array as $value) { _error_log("Object::deleteCachePattern file [{$value}]"); @unlink($value); } _session_start(); foreach ($_SESSION['user']['sessionCache'] as $key => $value) { if (preg_match($pattern, $key)) { _error_log("Object::deleteCachePattern session [{$key}]"); $_SESSION['user']['sessionCache'][$key] = null; unset($_SESSION['user']['sessionCache'][$key]); } } } public static function deleteALLCache() { global $__getAVideoCache; unset($__getAVideoCache); $tmpDir = self::getCacheDir(); rrmdir($tmpDir); self::deleteAllSessionCache(); self::setLastDeleteALLCacheTime(); } public static function getCacheDir($filename = '') { global $_getCacheDir, $global; if (!isset($_getCacheDir)) { $_getCacheDir = array(); } if (!empty($_getCacheDir[$filename])) { return $_getCacheDir[$filename]; } $tmpDir = getTmpDir(); $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $tmpDir .= "YPTObjectCache" . DIRECTORY_SEPARATOR; $filename = self::cleanCacheName($filename); if (!empty($filename)) { $tmpDir .= $filename . DIRECTORY_SEPARATOR; $domain = getDomain(); $tmpDir .= $domain . DIRECTORY_SEPARATOR; // make sure you separete http and https cache $protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http'; $tmpDir .= $protocol . DIRECTORY_SEPARATOR; if (class_exists("User_Location")) { $loc = User_Location::getThisUserLocation(); if (!empty($loc) && !empty($loc['country_code'])) { $tmpDir .= $loc['country_code'] . DIRECTORY_SEPARATOR; } } if (User::isLogged()) { if(User::isAdmin()){ $tmpDir .= 'admin_'.md5("admin".$global['salt']).DIRECTORY_SEPARATOR; }else{ $tmpDir .= 'user_'.md5("user".$global['salt']).DIRECTORY_SEPARATOR; } }else{ $tmpDir .= 'notlogged_'.md5("notlogged".$global['salt']).DIRECTORY_SEPARATOR; } } make_path($tmpDir); if (!file_exists($tmpDir . "index.html") && is_writable($tmpDir)) {// to avoid search into the directory file_put_contents($tmpDir . "index.html", time()); } $_getCacheDir[$filename] = $tmpDir; return $tmpDir; } public static function getCacheFileName($name) { global $global; $tmpDir = self::getCacheDir($name); $uniqueHash = md5($name . $global['salt']); // add salt for security reasons return $tmpDir . $uniqueHash . '.cache'; } public static function deleteCacheFromPattern($name) { $tmpDir = getTmpDir(); $name = self::cleanCacheName($name); $ignoreLocationDirectoryName = (strpos($name, DIRECTORY_SEPARATOR) !== false); $filePattern = $tmpDir . DIRECTORY_SEPARATOR . $name; foreach (glob("{$filePattern}*") as $filename) { unlink($filename); } self::deleteSessionCache($name); } /** * Make sure you start the session before any output * @param type $name * @param type $value */ public static function setSessionCache($name, $value) { $name = self::cleanCacheName($name); _session_start(); $_SESSION['user']['sessionCache'][$name]['value'] = json_encode($value); $_SESSION['user']['sessionCache'][$name]['time'] = time(); if (empty($_SESSION['user']['sessionCache']['time'])) { $_SESSION['user']['sessionCache']['time'] = time(); } } /** * * @param type $name * @param type $lifetime, if is = 0 it is unlimited * @return type */ public static function getSessionCache($name, $lifetime = 60) { $name = self::cleanCacheName($name); if (!empty($_GET['lifetime'])) { $lifetime = intval($_GET['lifetime']); } if (!empty($_SESSION['user']['sessionCache'][$name])) { if ((empty($lifetime) || time() - $lifetime <= $_SESSION['user']['sessionCache'][$name]['time'])) { $c = $_SESSION['user']['sessionCache'][$name]['value']; $json = _json_decode($c); if(is_string($json) && strtolower($json) === 'false'){ $json = false; } return $json; } _session_start(); unset($_SESSION['user']['sessionCache'][$name]); } return null; } public static function clearSessionCache() { unset($_SESSION['user']['sessionCache']); } private static function getLastDeleteALLCacheTimeFile() { $tmpDir = getTmpDir(); $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . "/"; $tmpDir .= "lastDeleteALLCacheTime.cache"; return $tmpDir; } public static function setLastDeleteALLCacheTime() { $file = self::getLastDeleteALLCacheTimeFile(); //_error_log("ObjectYPT::setLastDeleteALLCacheTime {$file}"); return file_put_contents($file, time()); } public static function getLastDeleteALLCacheTime() { global $getLastDeleteALLCacheTime; if (empty($getLastDeleteALLCacheTime)) { $getLastDeleteALLCacheTime = (int) @file_get_contents(self::getLastDeleteALLCacheTimeFile(), time()); } return $getLastDeleteALLCacheTime; } public static function checkSessionCacheBasedOnLastDeleteALLCacheTime() { /* var_dump( $session_var['time'], self::getLastDeleteALLCacheTime(), humanTiming($session_var['time']), humanTiming(self::getLastDeleteALLCacheTime()), $session_var['time'] <= self::getLastDeleteALLCacheTime()); * */ if (empty($_SESSION['user']['sessionCache']['time']) || $_SESSION['user']['sessionCache']['time'] <= self::getLastDeleteALLCacheTime()) { self::deleteAllSessionCache(); return false; } return true; } public static function deleteSessionCache($name) { $name = self::cleanCacheName($name); _session_start(); $_SESSION['user']['sessionCache'][$name] = null; unset($_SESSION['user']['sessionCache'][$name]); } public static function deleteAllSessionCache() { _session_start(); unset($_SESSION['user']['sessionCache']); } public function tableExists() { return self::isTableInstalled(); } public static function isTableInstalled($tableName = "") { global $global, $tableExists; if (empty($tableName)) { $tableName = static::getTableName(); } if (empty($tableName)) { return false; } if (!isset($tableExists[$tableName])) { $sql = "SHOW TABLES LIKE '" . $tableName . "'"; //_error_log("isTableInstalled: ({$sql})"); $res = sqlDAL::readSql($sql); $result = sqlDal::num_rows($res); sqlDAL::close($res); $tableExists[$tableName] = !empty($result); } return $tableExists[$tableName]; } } //abstract class Object extends ObjectYPT{}; diff --git a/objects/aVideoEncoder.json.php b/objects/aVideoEncoder.json.php index 5b2519c33..c3cf47305 100644 --- a/objects/aVideoEncoder.json.php +++ b/objects/aVideoEncoder.json.php @@ -1,229 +1,208 @@ error = true; global $global, $config; if (!isset($global['systemRootPath'])) { require_once '../videos/configuration.php'; } require_once $global['systemRootPath'] . 'objects/user.php'; require_once $global['systemRootPath'] . 'objects/video.php'; if (empty($_POST)) { $obj->msg = __("Your POST data is empty, maybe your video file is too big for the host"); _error_log($obj->msg); die(json_encode($obj)); } _error_log("aVideoEncoder.json: start"); if (empty($_POST['format']) || !in_array($_POST['format'], $global['allowedExtension'])) { _error_log("aVideoEncoder.json: Extension not allowed File " . __FILE__ . ": " . json_encode($_POST)); die(); } // pass admin user and pass $user = new User("", @$_POST['user'], @$_POST['password']); $user->login(false, true); if (!User::canUpload()) { _error_log("aVideoEncoder.json: Permission denied to receive a file: " . json_encode($_POST)); $obj->msg = __("Permission denied to receive a file: ") . json_encode($_POST); _error_log($obj->msg); die(json_encode($obj)); } if (!empty($_POST['videos_id']) && !Video::canEdit($_POST['videos_id'])) { _error_log("aVideoEncoder.json: Permission denied to edit a video: " . json_encode($_POST)); $obj->msg = __("Permission denied to edit a video: ") . json_encode($_POST); _error_log($obj->msg); die(json_encode($obj)); } _error_log("aVideoEncoder.json: start to receive: " . json_encode($_POST)); // check if there is en video id if yes update if is not create a new one $video = new Video("", "", @$_POST['videos_id']); if(!empty($video->getId()) && !empty($_REQUEST['first_request'])){ _error_log("aVideoEncoder.json: There is a new video to replace the existing one, we will delete the current files videos_id = ".$video->getId()); $video->removeVideoFiles(); } $obj->video_id = @$_POST['videos_id']; $title = $video->getTitle(); $description = $video->getDescription(); if (empty($title) && !empty($_POST['title'])) { $title = $video->setTitle($_POST['title']); } elseif (empty($title)) { $video->setTitle("Automatic Title"); } if (empty($description)) { $video->setDescription($_POST['description']); } if(!empty($_REQUEST['duration'])){ $duration = $video->getDuration(); if(empty($duration) || $duration === 'EE:EE:EE'){ $video->setDuration($_REQUEST['duration']); } } -$status = $video->getStatus(); -// if encoder requested a status -if (!empty($_POST['overrideStatus'])) { - $video->setStatus($_POST['overrideStatus']); -} else { // encoder did not provide a status - // if status is not unlisted - if ($status !== 'u' && $status !== 'a') { - if (empty($advancedCustom->makeVideosInactiveAfterEncode)) { - // set active or active+encoding - if (!empty($_POST['keepEncoding'])) { - $video->setStatus('k'); - } else { - $video->setStatus('a'); - } - - } elseif (empty($advancedCustom->makeVideosUnlistedAfterEncode)) { - // set active - $video->setStatus('u'); - } else { - $video->setStatus('i'); - } - } -} +$status = $video->setAutoStatus(); + $video->setVideoDownloadedLink($_POST['videoDownloadedLink']); _error_log("aVideoEncoder.json: Encoder receiving post " . json_encode($_POST)); //_error_log(print_r($_POST, true)); if (preg_match("/(mp3|wav|ogg)$/i", $_POST['format'])) { $type = 'audio'; $video->setType($type); } elseif (preg_match("/(mp4|webm|zip)$/i", $_POST['format'])) { $type = 'video'; $video->setType($type); } $videoFileName = $video->getFilename(); if (empty($videoFileName)) { $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($title)); $videoFileName = uniqid($mainName . "_YPTuniqid_", true); $video->setFilename($videoFileName); } $destination_local = Video::getStoragePath()."{$videoFileName}"; if (!empty($_FILES)) { _error_log("aVideoEncoder.json: Files " . json_encode($_FILES)); } else { _error_log("aVideoEncoder.json: Files EMPTY"); if (!empty($_REQUEST['downloadURL'])) { $_FILES['video']['tmp_name'] = downloadVideoFromDownloadURL($_REQUEST['downloadURL']); if (empty($_FILES['video']['tmp_name'])) { _error_log("aVideoEncoder.json: ******** Download ERROR " . $_REQUEST['downloadURL']); } } } if (!empty($_FILES['video']['error'])) { $phpFileUploadErrors = array( 0 => 'There is no error, the file uploaded with success', 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk.', 8 => 'A PHP extension stopped the file upload.', ); _error_log("aVideoEncoder.json: ******** Files ERROR " . $phpFileUploadErrors[$_FILES['video']['error']]); if (!empty($_POST['downloadURL'])) { $_FILES['video']['tmp_name'] = downloadVideoFromDownloadURL($_POST['downloadURL']); } } if (empty($_FILES['video']['tmp_name']) && !empty($_POST['chunkFile'])) { $_FILES['video']['tmp_name'] = $_POST['chunkFile']; } // get video file from encoder if (!empty($_FILES['video']['tmp_name'])) { $resolution = ""; if (!empty($_POST['resolution'])) { $resolution = "_{$_POST['resolution']}"; } $filename = "{$videoFileName}{$resolution}.{$_POST['format']}"; $fsize = filesize($_FILES['video']['tmp_name']); _error_log("aVideoEncoder.json: receiving video upload to {$filename} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")" . json_encode($_FILES)); decideMoveUploadedToVideos($_FILES['video']['tmp_name'], $filename); } else { // set encoding - $video->setStatus('e'); + $video->setStatus(Video::$statusEncoding); } if (!empty($_FILES['image']['tmp_name']) && !file_exists("{$destination_local}.jpg")) { if (!move_uploaded_file($_FILES['image']['tmp_name'], "{$destination_local}.jpg")) { $obj->msg = print_r(sprintf(__("Could not move image file [%s.jpg]"), $destination_local), true); _error_log("aVideoEncoder.json: " . $obj->msg); die(json_encode($obj)); } } if (!empty($_FILES['gifimage']['tmp_name']) && !file_exists("{$destination_local}.gif")) { if (!move_uploaded_file($_FILES['gifimage']['tmp_name'], "{$destination_local}.gif")) { $obj->msg = print_r(sprintf(__("Could not move gif image file [%s.gif]"), $destination_local), true); _error_log("aVideoEncoder.json: " . $obj->msg); die(json_encode($obj)); } } if (!empty($_POST['encoderURL'])) { $video->setEncoderURL($_POST['encoderURL']); } if (!empty($_POST['categories_id'])) { $video->setCategories_id($_POST['categories_id']); } $video_id = $video->save(); $video->updateDurationIfNeed(); $video->updateHLSDurationIfNeed(); if (!empty($_POST['usergroups_id'])) { if (!is_array($_POST['usergroups_id'])) { $_POST['usergroups_id'] = array($_POST['usergroups_id']); } UserGroups::updateVideoGroups($video_id, $_POST['usergroups_id']); } $obj->error = false; $obj->video_id = $video_id; _error_log("aVideoEncoder.json: Files Received for video {$video_id}: " . $video->getTitle()); die(json_encode($obj)); /* _error_log(print_r($_POST, true)); _error_log(print_r($_FILES, true)); var_dump($_POST, $_FILES); */ function downloadVideoFromDownloadURL($downloadURL) { global $global; _error_log("aVideoEncoder.json: Try to download " . $downloadURL); $file = url_get_contents($_POST['downloadURL']); if (strlen($file)<20000) { //it is not a video return false; } _error_log("aVideoEncoder.json: Got the download " . $downloadURL); if ($file) { $_FILES['video']['name'] = basename($downloadURL); $temp = Video::getStoragePath()."cache/tmpFile/" . $_FILES['video']['name']; _error_log("aVideoEncoder.json: save " . $temp); make_path($temp); file_put_contents($temp, $file); return $temp; } return false; } diff --git a/objects/aVideoEncoderNotifyIsDone.json.php b/objects/aVideoEncoderNotifyIsDone.json.php index b46e3a5ea..856bbc288 100644 --- a/objects/aVideoEncoderNotifyIsDone.json.php +++ b/objects/aVideoEncoderNotifyIsDone.json.php @@ -1,84 +1,68 @@ error = true; global $global, $config; if(!isset($global['systemRootPath'])){ require_once '../videos/configuration.php'; } require_once $global['systemRootPath'] . 'objects/user.php'; require_once $global['systemRootPath'] . 'objects/video.php'; $_POST['videos_id'] = intval($_POST['videos_id']); if (empty($_POST)) { $obj->msg = __("Your POST data is empty, maybe your video file is too big for the host"); _error_log($obj->msg); die(json_encode($obj)); } // pass admin user and pass $user = new User("", @$_POST['user'], @$_POST['password']); $user->login(false, true); if (!User::canUpload()) { $obj->msg = __("Permission denied to Notify Done: ") . print_r($_POST, true); _error_log($obj->msg); die(json_encode($obj)); } if(!Video::canEdit($_POST['videos_id'])){ $obj->msg = __("Permission denied to edit a video: ") . print_r($_POST, true); _error_log($obj->msg); die(json_encode($obj)); } Video::clearCache($_POST['videos_id']); // check if there is en video id if yes update if is not create a new one $video = new Video("", "", $_POST['videos_id']); $obj->video_id = $_POST['videos_id']; -if(empty($_POST['fail'])){ - // if encoder requested a status - if (!empty($_POST['overrideStatus'])) { - $video->setStatus($_POST['overrideStatus']); - } else { // encoder did not provide a status - $status = $video->getStatus(); - // if status is not unlisted - if($status!=='u' && $status !== 'a'){ - if(empty($advancedCustom->makeVideosInactiveAfterEncode)){ - // set active - $video->setStatus('a'); - }else if(empty($advancedCustom->makeVideosUnlistedAfterEncode)){ - // set active - $video->setStatus('u'); - }else{ - $video->setStatus('i'); - } - } - } -}else{ - $video->setStatus('i'); -} + +$video->setAutoStatus(Video::$statusActive); + $video_id = $video->save(); -if(empty($_POST['fail'])){ - AVideoPlugin::afterNewVideo($_POST['videos_id']); + +$video = new Video("", "", $video_id); + +if($video->getStatus() === Video::$statusActive){ + AVideoPlugin::afterNewVideo($video_id); } $obj->error = false; $obj->video_id = $video_id; Video::updateFilesize($video_id); // delete original files if any $originalFilePath = Video::getStoragePath()."original_" . $video->getFilename(); if(file_exists($originalFilePath)){ unlink($originalFilePath); } _error_log("Video is done notified {$video_id}: " . $video->getTitle()); Video::clearCache($video_id); die(json_encode($obj)); /* _error_log(print_r($_POST, true)); _error_log(print_r($_FILES, true)); var_dump($_POST, $_FILES); */ diff --git a/objects/aVideoQueueEncoder.json.php b/objects/aVideoQueueEncoder.json.php index 504f97b49..221c21954 100644 --- a/objects/aVideoQueueEncoder.json.php +++ b/objects/aVideoQueueEncoder.json.php @@ -1,182 +1,182 @@ error = true; global $global, $config; if (!isset($global['systemRootPath'])) { require_once '../videos/configuration.php'; } require_once $global['systemRootPath'] . 'objects/user.php'; require_once $global['systemRootPath'] . 'objects/video.php'; if (!User::canUpload()) { $obj->msg = __("Permission denied"); die(json_encode($obj)); } // A list of permitted file extensions $allowed = array('mp4', 'avi', 'mov', 'mkv', 'flv', 'mp3', 'm4a', 'wav', 'm4v', 'webm', 'wmv'); if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) { $updateVideoGroups = false; //echo "Success: \$_FILES OK\n"; $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION); if (!in_array(strtolower($extension), $allowed)) { //echo '{"status":"error", "msg":"File extension error [' . $_FILES['upl']['name'] . '], we allow only (' . implode(",", $allowed) . ')"}'; status(["status" => "error" , "msg" => "File extension error (" . $_FILES['upl']['name'] . "), we allow only (" . implode(",", $allowed) . ")"]); exit; } //echo "Success: file extension OK\n"; //chack if is an audio $type = "video"; if (strcasecmp($extension, 'mp3') == 0 || strcasecmp($extension, 'wav') == 0 || strcasecmp($extension, 'm4a') == 0) { $type = 'audio'; } //var_dump($extension, $type);exit; require_once $global['systemRootPath'] . 'objects/video.php'; //echo "Starting Get Duration\n"; $duration = Video::getDurationFromFile($_FILES['upl']['tmp_name']); // check if can upload video (about time limit storage) if (!empty($global['videoStorageLimitMinutes'])) { $maxDuration = $global['videoStorageLimitMinutes'] * 60; $currentStorageUsage = getSecondsTotalVideosLength(); $thisFile = parseDurationToSeconds($duration); $limitAfterThisFile = $currentStorageUsage + $thisFile; if ($maxDuration < $limitAfterThisFile) { status(["status" => "error", "msg" => "Sorry, your storage limit has run out." . "
[Max Duration: {$maxDuration} Seconds]" . "
[Current Srotage Usage: {$currentStorageUsage} Seconds]" . "
[This File Duration: {$thisFile} Seconds]" . "
[Limit after this file: {$limitAfterThisFile} Seconds]", "type" => '$_FILES Limit Error']); if (!empty($_FILES['upl']['videoId'])) { $video = new Video("", "", $_FILES['upl']['videoId']); $video->delete(); } exit; } } $path_parts = pathinfo($_FILES['upl']['name']); if (empty($path_parts['extension']) || !in_array(strtolower($path_parts['extension']), $global['allowedExtension'])) { _error_log("Extension not allowed File " . __FILE__ . ": " . json_encode($path_parts)); die(); } $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($path_parts['filename'])); $filename = uniqid($mainName . "_YPTuniqid_", true); $originalFilePath = Video::getStoragePath()."original_" . $filename; $video = new Video(preg_replace("/_+/", " ", $path_parts['filename']), $filename, @$_FILES['upl']['videoId']); $video->setDuration($duration); if ($type == 'audio') { $video->setType($type); } else { $video->setType("video"); } - $video->setStatus('e'); + $video->setStatus(Video::$statusEncoding); /* * set visibility for private videos */ if (array_key_exists('videoGroups', $_FILES['upl'])) { $video->setVideoGroups($_FILES['upl']['videoGroups']); $updateVideoGroups = true; } /* * set description (if given) */ if (!empty($_FILES['upl']['description'])) { $video->setDescription($_FILES['upl']['description']); } /* * set title (if given) */ if (!empty($_FILES['upl']['title'])) { $video->setTitle($_FILES['upl']['title']); $video->setClean_title($_FILES['upl']['title']); } else { /** * Make a better title and clean title */ $videoNewTitle = $video->getTitle(); $titleParts = explode("YPTuniqid", $videoNewTitle); $video->setTitle($titleParts[0]); $video->setClean_title($titleParts[0]); } $id = $video->save($updateVideoGroups); /** * Copy, rename or move original file * * copy: used from command line when -c option is included * rename: used with files which were downloaded directly into the videos directory (from other media sites) * move: default, used with uploaded files */ if (array_key_exists('copyOriginalFile', $_FILES['upl'])) { if (!copy($_FILES['upl']['tmp_name'], $originalFilePath)) { die("Error on copy(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")"); } } elseif (array_key_exists('dontMoveUploadedFile', $_FILES['upl'])) { if (!rename($_FILES['upl']['tmp_name'], $originalFilePath)) { die("Error on rename(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")"); } } elseif (!move_uploaded_file($_FILES['upl']['tmp_name'], $originalFilePath)) { if (!rename($_FILES['upl']['tmp_name'], $originalFilePath)) { die("Error on move_uploaded_file(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")"); } } $video = new Video('', '', $id); // send to encoder $queue = array(); $postFields = array(); if ($video->getType() == 'video') { if (AVideoPlugin::isEnabledByName("VideoHLS")) { $postFields['inputHLS'] = 1; }else{ $postFields['inputLow'] = 1; $postFields['inputSD'] = 1; $postFields['inputHD'] = 1; if (!empty($_FILES['upl']['webm'])) $postFields['webm'] = 1; } } else { $postFields['audioOnly'] = 1; $postFields['spectrum'] = 1; } if (!empty($_FILES['upl']['override_status'])) $postFields['override_status'] = $_FILES['upl']['override_status']; if (!empty($_FILES['upl']['update_video_id'])) $postFields['update_video_id'] = $_FILES['upl']['update_video_id']; $queue[] = $video->queue($postFields); //exec("/usr/bin/php -f videoEncoder.php {$_FILES['upl']['tmp_name']} {$filename} 1> Video::getStoragePath()."{$filename}_progress.txt 2>&1", $output, $return_val); //var_dump($output, $return_val); //echo '{"status":"success", "msg":"Your video (' . $filename . ') is encoding
' . $cmd . '", "filename":"' . $filename . '", "duration":"' . $duration . '"}'; status(["status" => "success" , "msg" => "Your video ($filename) is queue" , "filename" => "$filename" , "duration" => "$duration" , "queue" => json_encode($queue)]); //exit; } else { //echo '{"status":"error", "msg":' . json_encode($_FILES) . ', "type":"$_FILES Error"}'; status(["status" => "error", "msg" => print_r($_FILES, true), "type" => '$_FILES Error']); //exit; } diff --git a/objects/getTimes.json.php b/objects/getTimes.json.php index 71757441b..b65e2a988 100644 --- a/objects/getTimes.json.php +++ b/objects/getTimes.json.php @@ -1,14 +1,15 @@ _serverTime = time(); $obj->_serverDBTime = getDatabaseTime(); $obj->_serverTimeString = date('Y-m-d H:i:s'); $obj->_serverDBTimeString = date('Y-m-d H:i:s', getDatabaseTime()); +$obj->_serverTimezone = date_default_timezone_get(); die(json_encode($obj)); \ No newline at end of file diff --git a/objects/user.php b/objects/user.php index 319cc9cc9..f09233231 100644 --- a/objects/user.php +++ b/objects/user.php @@ -1,2370 +1,2395 @@ user = $user; if ($password !== false) { $this->password = $password; } else { $this->loadFromUser($user); } } else { // get data from id $this->load($id); } } public function getEmail() { return $this->email; } public function getUser() { return $this->user; } public function getAbout() { return str_replace(array('\\\\\\\n'), array("\n"), $this->about); } public function setAbout($about) { $this->about = xss_esc($about); } public function getPassword() { return $this->password; } public function getCanStream() { return $this->canStream; } public function setCanStream($canStream) { $this->canStream = (empty($canStream) || strtolower($canStream) === 'false') ? 0 : 1; } public function getCanViewChart() { return $this->canViewChart; } public function setCanViewChart($canViewChart) { $this->canViewChart = (empty($canViewChart) || strtolower($canViewChart) === 'false') ? 0 : 1; } public function getCanCreateMeet() { return $this->canCreateMeet; } public function setCanCreateMeet($canCreateMeet) { $this->canCreateMeet = (empty($canCreateMeet) || strtolower($canCreateMeet) === 'false') ? 0 : 1; ; } public function getCanUpload() { return $this->canUpload; } public function setCanUpload($canUpload) { $this->canUpload = (empty($canUpload) || strtolower($canUpload) === 'false') ? 0 : 1; } public function getAnalyticsCode() { return $this->analyticsCode; } public function setAnalyticsCode($analyticsCode) { preg_match("/(ua-\d{4,9}-\d{1,4})/i", $analyticsCode, $matches); if (!empty($matches[1])) { $this->analyticsCode = $matches[1]; } else { $this->analyticsCode = ""; } } public function getAnalytics() { $id = $this->getId(); $aCode = $this->getAnalyticsCode(); if (!empty($id) && !empty($aCode)) { $code = " "; } else { $code = ""; } return $code; } public function addExternalOptions($id, $value) { $eo = unserialize(base64_decode($this->externalOptions)); if (!is_array($eo)) { $eo = array(); } $eo[$id] = $value; $this->setExternalOptions($eo); return $this->save(); } public function removeExternalOptions($id) { $eo = unserialize(base64_decode($this->externalOptions)); unset($eo[$id]); $this->setExternalOptions($eo); return $this->save(); } public function setExternalOptions($options) { //we convert it to base64 to sanitize the input since we do not validate input from externalOptions $this->externalOptions = base64_encode(serialize($options)); } public function getExternalOption($id) { $eo = unserialize(base64_decode($this->externalOptions)); if (empty($eo[$id])) { return null; } return $eo[$id]; } private function load($id) { $id = intval($id); if (empty($id)) { return false; } $user = self::getUserDb($id); if (empty($user)) { return false; } foreach ($user as $key => $value) { $this->$key = $value; } return true; } private function loadFromUser($user) { $userLoaded = self::getUserDbFromUser($user); if (empty($userLoaded)) { return false; } _error_log("User::loadFromUser($user) "); _error_log("User::loadFromUser json " . json_encode(debug_backtrace())); foreach ($userLoaded as $key => $value) { $this->$key = $value; } return true; } public function loadSelfUser() { $this->load($this->getId()); } public static function getId() { if (self::isLogged()) { return $_SESSION['user']['id']; } else { return false; } } public static function getEmail_() { if (self::isLogged()) { return $_SESSION['user']['email']; } else { return false; } } public function getBdId() { return $this->id; } public static function updateSessionInfo() { if (self::isLogged()) { $user = self::getUserDb($_SESSION['user']['id']); $_SESSION['user'] = $user; } } public static function getName() { if (self::isLogged()) { return $_SESSION['user']['name']; } else { return false; } } public static function getUserName() { if (self::isLogged()) { return $_SESSION['user']['user']; } else { return false; } } public static function getUserChannelName() { if (self::isLogged()) { if (empty($_SESSION['user']['channelName'])) { $_SESSION['user']['channelName'] = self::_recommendChannelName(); $user = new User(User::getId()); $user->setChannelName($_SESSION['user']['channelName']); $user->save(); } return $_SESSION['user']['channelName']; } else { return false; } } public static function _recommendChannelName($name = "", $try = 0, $unknown = "", $users_id = 0) { if (empty($users_id)) { if (!empty(User::getId())) { $users_id = User::getId(); } } if (empty($users_id)) { $newChannelName = $name . "_" . uniqid(); if (strlen($newChannelName) > 40) { $newChannelName = uniqid(); } return $newChannelName; } if ($try > 10) { _error_log("User:_recommendChannelName too many tries ({$name}) (" . User::getId() . ") ", AVideoLog::$ERROR); return uniqid(); } if (empty($name)) { $name = self::getNameIdentification(); if ($name == __("Unknown User") && !empty($unknown)) { $name = $unknown; } $name = cleanString($name); } // in case is a email get only the username $parts = explode("@", $name); $name = $parts[0]; // do not exceed 36 chars to leave some room for the unique id; $name = substr($name, 0, 36); if (!Permissions::canAdminUsers()) { $user = self::getUserFromChannelName($name); if ($user && $user['id'] !== $users_id) { return self::_recommendChannelName($name . "_" . uniqid(), $try + 1); } } return $name; } public static function getUserFromChannelName($channelName) { $channelName = cleanString($channelName); global $global; $channelName = ($channelName); $sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($channelName)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { $user = cleanUpRowFromDatabase($user); return $user; } else { return false; } } /** * return an name to identify the user * @return String */ public static function getNameIdentification() { global $advancedCustomUser; if (self::isLogged()) { if (!empty(self::getName()) && empty($advancedCustomUser->doNotIndentifyByName)) { return self::getName(); } if (!empty(self::getMail()) && empty($advancedCustomUser->doNotIndentifyByEmail)) { return self::getMail(); } if (!empty(self::getUserName()) && empty($advancedCustomUser->doNotIndentifyByUserName)) { return self::getUserName(); } if (!empty(self::getUserChannelName())) { return self::getUserChannelName(); } } return __("Unknown User"); } /** * return an name to identify the user from database * @return String */ public function getNameIdentificationBd() { global $advancedCustomUser; if (!empty($this->name) && empty($advancedCustomUser->doNotIndentifyByName)) { return $this->name; } if (!empty($this->email) && empty($advancedCustomUser->doNotIndentifyByEmail)) { return $this->email; } if (!empty($this->user) && empty($advancedCustomUser->doNotIndentifyByUserName)) { return $this->user; } if (!empty($this->channelName)) { return $this->channelName; } return __("Unknown User"); } public static function getNameIdentificationById($id = "") { if (!empty($id)) { $user = new User($id); return $user->getNameIdentificationBd(); } return __("Unknown User"); } public static function getUserPass() { if (self::isLogged()) { return $_SESSION['user']['password']; } else { return false; } } public function _getName() { return $this->name; } public function getBdName() { return $this->_getName(); } public static function _getPhoto($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['photoURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['photoURL']; } if (!empty($photo)) { if (preg_match("/videos\/userPhoto\/.*/", $photo) && file_exists($global['systemRootPath'] . $photo)) { return $photo; } else { $photoPath = "/videos/userPhoto/photo{$id}.png"; $content = url_get_contents($photo); file_put_contents($global['systemRootPath'] . $photoPath, $content); $photo = $photoPath; } } if (empty($photo)) { $photo = "view/img/userSilhouette.jpg"; } return $photo; } public static function getPhoto($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['photoURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['photoURL']; } if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) { if (file_exists($global['systemRootPath'] . $photo)) { $photo = getCDN() . $photo . "?" . filemtime($global['systemRootPath'] . $photo); } else { $photo = ""; } } if (empty($photo)) { $photo = getCDN() . "view/img/userSilhouette.jpg"; } return $photo; } public static function _getOGImage($users_id) { return "/videos/userPhoto/photo{$users_id}_og_200X200.jpg"; } public static function deleteOGImage($users_id) { global $global; $photo = $global['systemRootPath'] . self::_getOGImage($users_id); @unlink($photo); } public static function getOGImage($users_id = "") { global $global; $photo = self::_getPhoto($users_id); if ($photo == "view/img/userSilhouette.jpg") { return getCDN() . "view/img/userSilhouette.jpg"; } if (empty($photo)) { return false; } $source = $global['systemRootPath'] . $photo; $destination = $global['systemRootPath'] . self::_getOGImage($users_id); convertImageToOG($source, $destination); return getCDN() . self::_getOGImage($users_id); } public static function getEmailVerifiedIcon($id = "") { global $advancedCustomUser; $mark = ""; if (!empty($advancedCustomUser->showEmailVerifiedMark)) { if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $verified = $user['emailVerified']; } } elseif (self::isLogged()) { $verified = $_SESSION['user']['emailVerified']; } if (!empty($verified)) { $mark .= ' '; } else { //return ''; $mark .= ''; } } if ($advancedCustomUser->Checkmark1Enabled) { if (User::externalOptionsFromUserID($id, "checkmark1")) { $mark .= " " . $advancedCustomUser->Checkmark1HTML; } } if ($advancedCustomUser->Checkmark2Enabled) { if (User::externalOptionsFromUserID($id, "checkmark2")) { $mark .= " " . $advancedCustomUser->Checkmark2HTML; } } if ($advancedCustomUser->Checkmark3Enabled) { if (User::externalOptionsFromUserID($id, "checkmark3")) { $mark .= " " . $advancedCustomUser->Checkmark3HTML; } } return $mark; } public function getPhotoDB() { global $global; $photo = self::getPhoto($this->id); return $photo; } public static function getBackground($id = "") { global $global; if (!empty($id)) { $user = self::findById($id); if (!empty($user)) { $photo = $user['backgroundURL']; } } elseif (self::isLogged()) { $photo = $_SESSION['user']['backgroundURL']; } if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) { if (file_exists($global['systemRootPath'] . $photo)) { $photo = getCDN() . $photo; } else { $photo = ""; } } if (empty($photo)) { $photo = getCDN() . "view/img/background.png"; } return $photo; } public static function getMail() { if (self::isLogged()) { return $_SESSION['user']['email']; } else { return false; } } public function save($updateUserGroups = false) { global $global, $config, $advancedCustom, $advancedCustomUser; if (is_object($config) && $config->currentVersionLowerThen('5.6')) { // they dont have analytics code return false; } if (empty($this->user) || empty($this->password)) { //echo "u:" . $this->user . "|p:" . strlen($this->password); _error_log('Error : ' . __("You need a user and passsword to register")); return false; } if (empty($this->isAdmin)) { $this->isAdmin = "false"; } if (empty($this->canStream)) { if (empty($this->id)) { // it is a new user if (empty($advancedCustomUser->newUsersCanStream)) { $this->canStream = "0"; } else { $this->canStream = "1"; } } else { $this->canStream = "0"; } } if (empty($this->canUpload)) { $this->canUpload = "0"; } if (empty($this->status)) { $this->status = 'a'; } if (empty($this->emailVerified)) { $this->emailVerified = "false"; } $user = ($this->user); $password = ($this->password); $name = ($this->name); $status = ($this->status); $this->about = preg_replace("/(\\\)+n/", "\n", $this->about); $this->channelName = self::_recommendChannelName($this->channelName, 0, $this->user, $this->id); $channelName = ($this->channelName); if (filter_var($this->donationLink, FILTER_VALIDATE_URL) === false) { $this->donationLink = ""; } if (!empty($this->id)) { $formats = "ssssiiii"; $values = array($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet); $sql = "UPDATE users SET user = ?, password = ?, " . "email = ?, name = ?, isAdmin = ?," . "canStream = ?,canUpload = ?,canCreateMeet = ?,"; if (isset($this->canViewChart)) { $formats .= "i"; $values[] = $this->canViewChart; $sql .= "canViewChart = ?, "; } $formats .= "ssssssissssssssssi"; $values[] = $this->status; $values[] = $this->photoURL; $values[] = $this->backgroundURL; $values[] = $this->recoverPass; $values[] = $this->about; $values[] = $this->channelName; $values[] = $this->emailVerified; $values[] = $this->analyticsCode; $values[] = $this->externalOptions; $values[] = $this->first_name; $values[] = $this->last_name; $values[] = $this->address; $values[] = $this->zip_code; $values[] = $this->country; $values[] = $this->region; $values[] = $this->city; $values[] = $this->donationLink; $values[] = $this->id; $sql .= "status = ?, " . "photoURL = ?, backgroundURL = ?, " . "recoverPass = ?, about = ?, " . " channelName = ?, emailVerified = ? , analyticsCode = ?, externalOptions = ? , " . " first_name = ? , last_name = ? , address = ? , zip_code = ? , country = ? , region = ? , city = ? , donationLink = ? , " . " modified = now() WHERE id = ?"; } else { $formats = "ssssiiiissssss"; $values = array($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet, $status, $this->photoURL, $this->recoverPass, $channelName, $this->analyticsCode, $this->externalOptions); $sql = "INSERT INTO users (user, password, email, name, isAdmin, canStream, canUpload, canCreateMeet, canViewChart, status,photoURL,recoverPass, created, modified, channelName, analyticsCode, externalOptions) " . " VALUES (?,?,?,?,?,?,?,?, false, " . "?,?,?, now(), now(),?,?,?)"; } $insert_row = sqlDAL::writeSql($sql, $formats, $values); if ($insert_row) { if (empty($this->id)) { $id = $global['mysqli']->insert_id; if (!empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) { self::sendVerificationLink($id); } } else { $id = $this->id; } if ($updateUserGroups) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; // update the user groups UserGroups::updateUserGroups($id, $this->userGroups); } return $id; } else { _error_log(' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql"); return false; } } public static function getChannelOwner($channelName) { global $global; $channelName = ($channelName); $sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($channelName)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $result = cleanUpRowFromDatabase($result); $user = $result; } else { $user = false; } return $user; } public static function getFromUsername($user) { global $global; $user = ($user); $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $result = cleanUpRowFromDatabase($result); $user = $result; } else { $user = false; } return $user; } private static function setCacheWatchVideo($cacheName, $value) { if (!User::isLogged()) { ObjectYPT::setCache($cacheName, $value); ; } else { ObjectYPT::setSessionCache($cacheName, $value); } } public static function canWatchVideo($videos_id) { $cacheName = "canWatchVideo$videos_id"; if (!User::isLogged()) { $cacheName = "canWatchVideoNOTLOGED$videos_id"; $cache = ObjectYPT::getCache($cacheName, 3600); } else { $cache = ObjectYPT::getSessionCache($cacheName, 600); } if (isset($cache)) { if($cache === 'false'){ $cache = false; } return $cache; } if (empty($videos_id)) { _error_log("User::canWatchVideo Video is empty ({$videos_id})"); return false; } if (User::isAdmin()) { return true; } $video = new Video("", "", $videos_id); if ($video->getStatus() === 'i') { _error_log("User::canWatchVideo Video is inactive ({$videos_id})"); self::setCacheWatchVideo($cacheName, false); return false; } $user = new User($video->getUsers_id()); if ($user->getStatus() === 'i') { _error_log("User::canWatchVideo User is inactive ({$videos_id})"); self::setCacheWatchVideo($cacheName, false); return false; } if (AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) { self::setCacheWatchVideo($cacheName, true); return true; } // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { // check if any plugin restrict access to this video if (!AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) { if (User::isLogged()) { _error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [" . User::getId() . "] can not see ({$videos_id})"); } else { _error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [not logged] can not see ({$videos_id})"); } self::setCacheWatchVideo($cacheName, false); return false; } else { self::setCacheWatchVideo($cacheName, true); return true; // the video is public } } if (!User::isLogged()) { _error_log("User::canWatchVideo You are not logged so can not see ({$videos_id}) session_id=" . session_id() . " SCRIPT_NAME=" . $_SERVER["SCRIPT_NAME"] . " IP = " . getRealIpAddr()); self::setCacheWatchVideo($cacheName, false); return false; } // if is not public check if the user is on one of its groups $rowsUser = UserGroups::getUserGroups(User::getId()); foreach ($rows as $value) { foreach ($rowsUser as $value2) { if ($value['id'] === $value2['id']) { self::setCacheWatchVideo($cacheName, true); return true; } } } _error_log("User::canWatchVideo The user " . User::getId() . " is not on any of the user groups ({$videos_id}) " . json_encode($rows)); self::setCacheWatchVideo($cacheName, false); return false; } public static function canWatchVideoWithAds($videos_id) { if (empty($videos_id)) { _error_log("User::canWatchVideo (videos_id is empty) " . $videos_id); return false; } if (User::isAdmin()) { return true; } if (AVideoPlugin::userCanWatchVideoWithAds(User::getId(), $videos_id)) { //_error_log("User::userCanWatchVideoWithAds (can) " . User::getId() . " " . $videos_id); return true; } _error_log("User::userCanWatchVideoWithAds (No can not) " . User::getId() . " " . $videos_id); if (self::canWatchVideo($videos_id)) { //_error_log("User::canWatchVideo (can) " . $videos_id); return true; } _error_log("User::canWatchVideo (No can not) " . $videos_id); return false; } public function delete() { if (!self::isAdmin()) { return false; } // cannot delete yourself if (self::getId() === $this->id) { return false; } global $global; if (!empty($this->id)) { $sql = "DELETE FROM users WHERE id = ?"; } else { return false; } return sqlDAL::writeSql($sql, "i", array($this->id)); } const USER_LOGGED = 0; const USER_NOT_VERIFIED = 1; const USER_NOT_FOUND = 2; const CAPTCHA_ERROR = 3; const REQUIRE2FA = 4; public function login($noPass = false, $encodedPass = false, $ignoreEmailVerification = false) { if (User::isLogged()) { return false; } global $global, $advancedCustom, $advancedCustomUser, $config; if (strtolower($encodedPass) === 'false') { $encodedPass = false; } //_error_log("user::login: noPass = $noPass, encodedPass = $encodedPass, this->user, $this->user " . getRealIpAddr()); if ($noPass) { $user = $this->find($this->user, false, true); } else { $user = $this->find($this->user, $this->password, true, $encodedPass); } if (!self::checkLoginAttempts()) { return self::CAPTCHA_ERROR; } ObjectYPT::clearSessionCache(); _session_start(); // check for multiple logins attempts to prevent hacking end // if user is not verified if (empty($ignoreEmailVerification) && !empty($user) && empty($user['isAdmin']) && empty($user['emailVerified']) && !empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) { unset($_SESSION['user']); self::sendVerificationLink($user['id']); return self::USER_NOT_VERIFIED; } elseif ($user) { $_SESSION['user'] = $user; $this->setLastLogin($_SESSION['user']['id']); $rememberme = 0; if ((!empty($_POST['rememberme']) && $_POST['rememberme'] == "true") || !empty($_COOKIE['rememberme'])) { $expires = strtotime("+ 1 year"); $rememberme = 1; } else { $expires = 0; } _setcookie("rememberme", $rememberme, $expires); _setcookie("user", $user['user'], $expires); _setcookie("pass", $user['password'], $expires); AVideoPlugin::onUserSignIn($_SESSION['user']['id']); $_SESSION['loginAttempts'] = 0; session_write_close(); return self::USER_LOGGED; } else { unset($_SESSION['user']); return self::USER_NOT_FOUND; } } public static function isCaptchaNeed() { global $advancedCustomUser; // check for multiple logins attempts to prevent hacking if (!empty($_SESSION['loginAttempts']) && !empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) { if (isMobile()) { $advancedCustomUser->requestCaptchaAfterLoginsAttempts += 10; } if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) { return true; } } return false; } public static function checkLoginAttempts() { global $advancedCustomUser, $global; // check for multiple logins attempts to prevent hacking if (empty($_SESSION['loginAttempts'])) { _session_start(); $_SESSION['loginAttempts'] = 0; } if (!empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) { _session_start(); $_SESSION['loginAttempts']++; if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) { if (empty($_POST['captcha'])) { return false; } require_once $global['systemRootPath'] . 'objects/captcha.php'; if (!Captcha::validation($_POST['captcha'])) { return false; } } } return true; } public static function getCaptchaFormIfNeed() { // check for multiple logins attempts to prevent hacking if (self::isCaptchaNeed()) { return self::getCaptchaForm(); } return ""; } public static function getCaptchaForm($uid = "") { global $global; return '
' . '
'; } private function setLastLogin($user_id) { global $global; if (empty($user_id)) { die('Error : setLastLogin '); } $sql = "UPDATE users SET lastLogin = now(), modified = now() WHERE id = ?"; return sqlDAL::writeSql($sql, "i", array($user_id)); } public static function logoff() { global $global, $justLogoff; $justLogoff = true; _session_start(); ObjectYPT::deleteAllSessionCache(); _unsetcookie('rememberme'); _unsetcookie('user'); _unsetcookie('pass'); unset($_SESSION['user']); } private static function recreateLoginFromCookie() { global $justLogoff, $justTryToRecreateLoginFromCookie; if (empty($justTryToRecreateLoginFromCookie) && empty($justLogoff) && empty($_SESSION['user']['id'])) { $justTryToRecreateLoginFromCookie = 1; // first check if the LoginControl::singleDeviceLogin is enabled, if it is only recreate login if the device is the last device if ($obj = AVideoPlugin::getDataObjectIfEnabled("LoginControl")) { if (!empty($obj->singleDeviceLogin)) { if (!LoginControl::isLoggedFromSameDevice()) { _error_log("user::recreateLoginFromCookie: LoginControl and the last logged device is different: " . $_COOKIE['user'] . ""); self::logoff(); return false; } } } if ((!empty($_COOKIE['user'])) && (!empty($_COOKIE['pass'])) && (!empty($_COOKIE['rememberme']))) { $user = new User(0, $_COOKIE['user'], false); $user->setPassword($_COOKIE['pass'], true); // $dbuser = self::getUserDbFromUser($_COOKIE['user']); $resp = $user->login(false, true); _error_log("user::recreateLoginFromCookie: do cookie-login: " . $_COOKIE['user'] . " result: " . $resp); if (0 == $resp) { _error_log("success " . $_SESSION['user']['id']); } else { _error_log("user::recreateLoginFromCookie: do logoff: " . $_COOKIE['user'] . " result: " . $resp); self::logoff(); } } } } public static function isLogged() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['id']); } public static function isVerified() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['emailVerified']); } public static function isAdmin() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['isAdmin']); } public static function canStream() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['isAdmin']) || !empty($_SESSION['user']['canStream']); } public static function externalOptions($id) { if (!empty($_SESSION['user']['externalOptions'])) { $externalOptions = unserialize(base64_decode($_SESSION['user']['externalOptions'])); if (isset($externalOptions[$id])) { if ($externalOptions[$id] == "true") { $externalOptions[$id] = true; } elseif ($externalOptions[$id] == "false") { $externalOptions[$id] = false; } return $externalOptions[$id]; } } return false; } public static function externalOptionsFromUserID($users_id, $id) { $user = self::findById($users_id); if ($user) { if (!is_null($user['externalOptions'])) { $externalOptions = unserialize(base64_decode($user['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($id != $k) { continue; } if ($v == "true") { $v = 1; } elseif ($v == "false") { $v = 0; } return $v; } } } } return false; } public function thisUserCanStream() { if ($this->status === 'i') { return false; } return !empty($this->isAdmin) || !empty($this->canStream); } private function find($user, $pass, $mustBeactive = false, $encodedPass = false) { global $global, $advancedCustom; $formats = ""; $values = array(); $sql = "SELECT * FROM users WHERE user = ? "; $formats .= "s"; $values[] = $user; if ($mustBeactive) { $sql .= " AND status = 'a' "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, $formats, $values, true); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { if ($pass !== false) { if (!encryptPasswordVerify($pass, $result['password'], $encodedPass)) { if (!empty($advancedCustom) && $advancedCustom->enableOldPassHashCheck) { _error_log("Password check new hash pass does not match, trying MD5"); return $this->find_Old($user, $pass, $mustBeactive, $encodedPass); } else { return false; } } } $user = $result; } else { _error_log("Password check new hash user not found"); //check if is the old password style $user = false; //$user = false; } return $user; } /** * this is the deprecated function, with week password * @global type $global * @param type $user * @param type $pass * @param type $mustBeactive * @param type $encodedPass * @return boolean */ private function find_Old($user, $pass, $mustBeactive = false, $encodedPass = false) { global $global; $formats = ""; $values = array(); $sql = "SELECT * FROM users WHERE user = ? "; $formats .= "s"; $values[] = $user; if ($mustBeactive) { $sql .= " AND status = 'a' "; } if ($pass !== false) { if (!$encodedPass || $encodedPass === 'false') { _error_log("Password check Old not encoded pass"); $passEncoded = md5($pass); } else { _error_log("Password check Old encoded pass"); $passEncoded = $pass; } $sql .= " AND password = ? "; $formats .= "s"; $values[] = $passEncoded; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, $formats, $values, true); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($result)) { if (!$encodedPass || $encodedPass === 'false') { //update the password $u = new User($result['id']); $u->setPassword($pass); $u->save(); $result['password'] = $u->getPassword(); } $user = $result; } else { $user = false; } if (empty($user)) { _error_log("Password check Old not found"); } else { _error_log("Password check Old found"); } return $user; } private static function findById($id) { global $global; $id = intval($id); if (empty($id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($id)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $user = $result; } else { $user = false; } return $user; } public static function findByEmail($email) { global $global; $email = trim($email); if (empty($email)) { return false; } $sql = "SELECT * FROM users WHERE email = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($email)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { $user = $result; } else { $user = false; } return $user; } private static function getUserDb($id) { global $global; $id = intval($id); if (empty($id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1;"; $res = sqlDAL::readSql($sql, "i", array($id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } private static function getUserDbFromUser($user) { global $global; if (empty($user)) { return false; } $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } public static function getUserFromID($users_id) { global $global; if (empty($users_id)) { return false; } $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($users_id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { $user['groups'] = UserGroups::getUserGroups($user['id']); $user['identification'] = self::getNameIdentificationById($user['id']); $user['photo'] = self::getPhoto($user['id']); $user['background'] = self::getBackground($user['id']); $user['tags'] = self::getTags($user['id']); $user['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $user['name']); $user['isEmailVerified'] = $user['emailVerified']; if (!is_null($user['externalOptions'])) { $externalOptions = unserialize(base64_decode($user['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($v == "true") { $v = 1; } elseif ($v == "false") { $v = 0; } $user[$k] = $v; } } } unset($user['password']); unset($user['recoverPass']); if (!Permissions::canAdminUsers() && $user['id'] !== User::getId()) { unset($user['first_name']); unset($user['last_name']); unset($user['address']); unset($user['zip_code']); unset($user['country']); unset($user['region']); unset($user['city']); } $user = $user; return $user; } return false; } public static function getUserFromEmail($email) { $email = trim($email); $sql = "SELECT * FROM users WHERE email = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($email)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user; } return false; } public function setUser($user) { global $advancedCustomUser; if (empty($advancedCustomUser->userCanChangeUsername)) { if (!empty($this->user)) { return false; } } $this->user = strip_tags($user); } public function setName($name) { $this->name = strip_tags($name); } public function setEmail($email) { global $advancedCustomUser; $email = strip_tags($email); if (!empty($advancedCustomUser->emailMustBeUnique)) { if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } $userFromEmail = User::getUserFromEmail($email); if (!empty($userFromEmail)) { return false; } } $this->email = $email; return true; } public function setPassword($password, $doNotEncrypt = false) { if (!empty($password)) { if ($doNotEncrypt) { $this->password = ($password); } else { $this->password = encryptPassword($password); } } } public function setIsAdmin($isAdmin) { if (empty($isAdmin) || $isAdmin === "false" || !User::isAdmin()) { $isAdmin = "0"; } else { $isAdmin = "1"; } $this->isAdmin = $isAdmin; } public function setStatus($status) { $this->status = strip_tags($status); } public function getPhotoURL() { return $this->photoURL; } public function setPhotoURL($photoURL) { $this->photoURL = strip_tags($photoURL); } public static function getAllUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } $users_groups_id = intval($users_groups_id); if (empty($users_groups_id)) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users u WHERE 1=1 "; $sql .= " AND (id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); if(!empty($ids) && is_array($ids)){ $ids = array_unique($ids); $sql .= " OR id IN ('". implode("','", $ids)."') "; } $sql .= " ) "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND u.status = 'i' "; } else { $sql .= " AND u.status = 'a' "; } } $sql .= BootGrid::getSqlFromPost($searchFields); $user = array(); require_once $global['systemRootPath'] . 'objects/userGroups.php'; $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = self::getUserInfoFromRow($row); } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } public static function getTotalUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } $users_groups_id = intval($users_groups_id); if (empty($users_groups_id)) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT id FROM users WHERE 1=1 "; $sql .= " AND (id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) "; $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); if(!empty($ids) && is_array($ids)){ $ids = array_unique($ids); $sql .= " OR id IN ('". implode("','", $ids)."') "; } $sql .= " ) "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user')); $res = sqlDAL::readSql($sql); $result = sqlDal::num_rows($res); sqlDAL::close($res); return $result; } public static function getAllUsers($ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users WHERE 1=1 "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlFromPost($searchFields); $user = array(); require_once $global['systemRootPath'] . 'objects/userGroups.php'; $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = self::getUserInfoFromRow($row); } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } public static function getAllActiveUsersThatCanUpload() { if (!Permissions::canAdminUsers()) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users WHERE 1=1 AND status = 'a' AND (canUpload = 1 OR isAdmin = 1) "; $user = array(); $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = $row; } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } private static function getUserInfoFromRow($row) { $row['groups'] = UserGroups::getUserGroups($row['id']); $row['identification'] = self::getNameIdentificationById($row['id']); $row['photo'] = self::getPhoto($row['id']); $row['background'] = self::getBackground($row['id']); $row['tags'] = self::getTags($row['id']); $row['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['name']); $row['isEmailVerified'] = $row['emailVerified']; if (!is_null($row['externalOptions'])) { $externalOptions = unserialize(base64_decode($row['externalOptions'])); if (is_array($externalOptions) && sizeof($externalOptions) > 0) { foreach ($externalOptions as $k => $v) { if ($v == "true") { $v = 1; } elseif ($v == "false") { $v = 0; } $row[$k] = $v; } } } unset($row['password']); unset($row['recoverPass']); if (!Permissions::canAdminUsers() && $row['id'] !== User::getId()) { unset($row['first_name']); unset($row['last_name']); unset($row['address']); unset($row['zip_code']); unset($row['country']); unset($row['region']); unset($row['city']); } return $row; } public static function getAllUsersThatHasVideos($ignoreAdmin = false) { if (!self::isAdmin() && !$ignoreAdmin) { return false; } global $global; $sql = "SELECT * FROM users u WHERE status = 'a' AND (canUpload = 1 || isAdmin = 1) AND " . " (SELECT count(id) FROM videos where users_id = u.id )>0 "; $user = array(); $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = $row; } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } public static function getTotalUsers($ignoreAdmin = false, $status = "") { if (!Permissions::canAdminUsers() && !$ignoreAdmin) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT id FROM users WHERE 1=1 "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND status = 'i' "; } else { $sql .= " AND status = 'a' "; } } $sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user')); $res = sqlDAL::readSql($sql); $result = sqlDal::num_rows($res); sqlDAL::close($res); return $result; } public static function userExists($user) { global $global; $user = ($user); $sql = "SELECT * FROM users WHERE user = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($user)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user['id']; } else { return false; } } public static function idExists($users_id) { global $global; $users_id = intval($users_id); $sql = "SELECT * FROM users WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($users_id)); $user = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($user != false) { return $user['id']; } else { return false; } } public static function createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false) { global $global, $advancedCustomUser; $userId = 0; if (!$userId = self::userExists($user)) { if (empty($pass)) { $pass = uniqid(); } $pass = encryptPassword($pass); $userObject = new User(0, $user, $pass); $userObject->setEmail($email); $userObject->setName($name); $userObject->setIsAdmin($isAdmin); $userObject->setPhotoURL($photoURL); $userObject->setEmailVerified($emailVerified); $userId = $userObject->save(); if (!empty($userId)) { if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup UserGroups::updateUserGroups($userId, array($advancedCustomUser->userDefaultUserGroup->value), true); } } return $userId; } else { if ($emailVerified) { $userObj = new User($userId); if (!$userObj->getEmailVerified()) { $userObj->setEmailVerified(1); $userObj->save(); } } } return $userId; } public function getRecoverPass() { return $this->recoverPass; } public function setRecoverPass($forceChange = false) { // let the same recover pass if it was 10 minutes ago if (!$this->isRecoverPassExpired($this->recoverPass) && empty($forceChange) && !empty($this->recoverPass) && !empty($recoverPass) && !empty($this->modified) && strtotime($this->modified) > strtotime("-10 minutes")) { return $this->recoverPass; } $this->recoverPass = $this->createRecoverPass(); return $this->recoverPass; } private function createRecoverPass($secondsValid = 600) { $json = new stdClass(); $json->valid = strtotime("+{$secondsValid} seconds"); return encryptString(json_encode($json)); } function checkRecoverPass($recoverPass) { if ($this->recoverPass === $recoverPass) { if (!$this->isRecoverPassExpired($recoverPass)) { _error_log('checkRecoverPass success: ' . $this->user . ' ' . getRealIpAddr()); return true; } } return false; } function isRecoverPassExpired($recoverPass) { $string = decryptString($recoverPass); if ($string) { $json = _json_decode($string); if (is_object($json)) { if (time() < $json->valid) { return false; } } } return true; } public static function canUpload($doNotCheckPlugins = false) { global $global, $config, $advancedCustomUser; if (Permissions::canModerateVideos()) { return true; } if (User::isAdmin()) { return true; } if (empty($doNotCheckPlugins) && !AVideoPlugin::userCanUpload(User::getId())) { return false; } if (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && !User::isVerified()) { return false; } if ($config->getAuthCanUploadVideos()) { return self::isLogged(); } if (self::isLogged() && !empty($_SESSION['user']['canUpload'])) { return true; } return self::isAdmin(); } public static function canViewChart() { global $global, $config; if (self::isLogged() && !empty($_SESSION['user']['canViewChart'])) { return true; } return self::isAdmin(); } public static function canCreateMeet() { global $global, $config; if (self::isLogged() && !empty($_SESSION['user']['canCreateMeet'])) { return true; } return self::isAdmin(); } public static function canComment() { global $global, $config, $advancedCustomUser; if (self::isAdmin()) { return true; } if (Permissions::canAdminComment()) { return true; } if ($config->getAuthCanComment()) { if (empty($advancedCustomUser->unverifiedEmailsCanNOTComment)) { return self::isLogged(); } else { return self::isVerified(); } } return false; } public static function canSeeCommentTextarea() { global $global, $config; if (!$config->getAuthCanComment()) { if (!self::isAdmin()) { return false; } } return true; } public function getUserGroups() { return $this->userGroups; } public function setUserGroups($userGroups) { if (is_array($userGroups)) { $this->userGroups = $userGroups; } } public function getIsAdmin() { return $this->isAdmin; } public function getStatus() { return $this->status; } /** * * @param type $user_id * text * label Default Primary Success Info Warning Danger */ public static function getTags($user_id) { $user = new User($user_id); $tags = array(); if ($user->getIsAdmin()) { $obj = new stdClass(); $obj->type = "info"; $obj->text = __("Admin"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "default"; $obj->text = __("Regular User"); $tags[] = $obj; } if ($user->getStatus() == "a") { $obj = new stdClass(); $obj->type = "success"; $obj->text = __("Active"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "danger"; $obj->text = __("Inactive"); $tags[] = $obj; } if ($user->getEmailVerified()) { $obj = new stdClass(); $obj->type = "success"; $obj->text = __("E-mail Verified"); $tags[] = $obj; } else { $obj = new stdClass(); $obj->type = "warning"; $obj->text = __("E-mail Not Verified"); $tags[] = $obj; } global $global; if (!empty($global['systemRootPath'])) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; } else { require_once 'userGroups.php'; } $groups = UserGroups::getUserGroups($user_id); foreach ($groups as $value) { $obj = new stdClass(); $obj->type = "warning"; $obj->text = $value['group_name']; $tags[] = $obj; } return $tags; } public function getBackgroundURL() { global $global; $this->backgroundURL = self::getBackgroundURLFromUserID($this->id); return $this->backgroundURL; } public static function getBackgroundURLFromUserID($users_id = 0) { if (empty($users_id)) { $users_id = User::getId(); } global $global; $backgroundURL = "videos/userPhoto/background{$users_id}.jpg"; if (!file_exists($global['systemRootPath'] . $backgroundURL)) { $backgroundURL = "videos/userPhoto/background{$users_id}.png"; } if (!file_exists($global['systemRootPath'] . $backgroundURL)) { $backgroundURL = "view/img/background.jpg"; } return $backgroundURL; } public function setBackgroundURL($backgroundURL) { $this->backgroundURL = strip_tags($backgroundURL); } public function getChannelName() { if (empty($this->channelName)) { $this->channelName = self::_recommendChannelName($this->channelName); $this->save(); } return $this->channelName; } public static function _getUserChannelName($users_id = 0) { global $global, $config; if (empty($users_id)) { $users_id = self::getId(); } $user = new User($users_id); if (empty($user)) { return false; } return $user->getChannelName(); } public function getEmailVerified() { return intval($this->emailVerified); } public static function validateChannelName($channelName) { return trim(preg_replace("/[^0-9A-Z_]/i", "", ucwords($channelName))); } /** * * @param type $channelName * @return boolean return true is is unique */ public function setChannelName($channelName) { $channelName = self::validateChannelName($channelName); $user = static::getChannelOwner($channelName); if (!empty($user)) { // if the channel name exists and it is not from this user, rename the channel name if (empty($this->id) || $user['id'] != $this->id) { return false; } } $this->channelName = xss_esc($channelName); return true; } public function setEmailVerified($emailVerified) { $this->emailVerified = (empty($emailVerified) || strtolower($emailVerified) === 'false') ? 0 : 1; } public static function getChannelLink($users_id = 0) { global $global; $name = self::_getChannelName($users_id); if (empty($name)) { return false; } $link = "{$global['webSiteRootURL']}channel/" . urlencode($name); return $link; } public static function getChannelLinkFromChannelName($channelName) { global $global; $link = "{$global['webSiteRootURL']}channel/" . urlencode($channelName); return $link; } public static function _getChannelName($users_id = 0) { global $global, $config; if (empty($users_id)) { $users_id = self::getId(); } $user = new User($users_id); if (empty($user)) { return false; } if (empty($user->getChannelName())) { $name = $user->getBdId(); } else { $name = $user->getChannelName(); } return $name; } public static function sendVerificationLink($users_id) { global $global, $advancedCustomUser; //Only send the verification email each 30 minutes if (!empty($_SESSION["sendVerificationLink"][$users_id]) && time() - $_SESSION["sendVerificationLink"][$users_id] > 1800) { _error_log("sendVerificationLink: Email already sent, we will wait 30 min {$users_id}"); return true; } $config = new Configuration(); $user = new User($users_id); $code = urlencode(static::createVerificationCode($users_id)); //Create a new PHPMailer instance if (!is_object($config)) { _error_log("sendVerificationLink: config is not a object " . json_encode($config)); return false; } $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); $email = $user->getEmail(); try { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); //$mail->SMTPDebug = 4; //Set who the message is to be sent from $mail->setFrom($contactEmail, $webSiteTitle); //Set who the message is to be sent to $mail->addAddress($email); //Set the subject line $mail->Subject = __('Please Verify Your E-mail ') . $webSiteTitle; $msg = sprintf(__("Hi %s"), $user->getName()); $msg .= "

" . __($advancedCustomUser->verificationMailTextLine1); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine2), $webSiteTitle); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine3), $webSiteTitle); $msg .= "

" . sprintf(__($advancedCustomUser->verificationMailTextLine4)); $msg .= "

" . " " . __("Verify") . ""; $mail->msgHTML($msg); $resp = $mail->send(); if (!$resp) { _error_log("sendVerificationLink Error Info: {$mail->ErrorInfo}"); } else { _session_start(); $_SESSION["sendVerificationLink"][$users_id] = time(); } return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } return false; } public static function verifyCode($code) { global $global; $obj = static::decodeVerificationCode($code); $salt = hash('sha256', $global['salt']); if ($salt !== $obj->salt) { return false; } $user = new User($obj->users_id); $recoverPass = $user->getRecoverPass(); if ($recoverPass == $obj->recoverPass) { $user->setEmailVerified(1); return $user->save(); } return false; } public static function createVerificationCode($users_id) { global $global; $obj = new stdClass(); $obj->users_id = $users_id; $obj->salt = hash('sha256', $global['salt']); $user = new User($users_id); $obj->recoverPass = $user->setRecoverPass(); $user->save(); return base64_encode(json_encode($obj)); } public static function decodeVerificationCode($code) { $obj = _json_decode(base64_decode($code)); return $obj; } public function getFirst_name() { return $this->first_name; } public function getLast_name() { return $this->last_name; } public function getAddress() { return $this->address; } public function getZip_code() { return $this->zip_code; } public function getCountry() { return $this->country; } public function getRegion() { return $this->region; } public function getCity() { return $this->city; } public function setFirst_name($first_name) { $this->first_name = $first_name; } public function setLast_name($last_name) { $this->last_name = $last_name; } public function setAddress($address) { $this->address = $address; } public function setZip_code($zip_code) { $this->zip_code = $zip_code; } public function setCountry($country) { $this->country = $country; } public function setRegion($region) { $this->region = $region; } public function setCity($city) { $this->city = $city; } public static function getDocumentImage($users_id) { $row = static::getBlob($users_id, User::$DOCUMENT_IMAGE_TYPE); if (!empty($row['blob'])) { return $row['blob']; } return false; } public static function saveDocumentImage($image, $users_id) { $row = static::saveBlob($image, $users_id, User::$DOCUMENT_IMAGE_TYPE); if (!empty($row['blob'])) { return $row['blob']; } return false; } public static function getBlob($users_id, $type) { global $global; $sql = "SELECT * FROM users_blob WHERE users_id = ? AND `type` = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "is", array($users_id, $type)); $result = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $result; } public static function saveBlob($blob, $users_id, $type) { global $global; $row = self::getBlob($users_id, $type); $null = null; if (!empty($row['id'])) { $sql = "UPDATE users_blob SET `blob` = ? , modified = now() WHERE id = ?"; $stmt = $global['mysqli']->prepare($sql); $stmt->bind_param('bi', $null, $row['id']); } else { $sql = "INSERT INTO users_blob (`blob`, users_id, `type`, modified, created) VALUES (?,?,?, now(), now())"; $stmt = $global['mysqli']->prepare($sql); $stmt->bind_param('bis', $null, $users_id, $type); } $stmt->send_long_data(0, $blob); return $stmt->execute(); } public static function deleteBlob($users_id, $type) { global $global; $row = self::getBlob($users_id, $type); if (!empty($row['id'])) { $sql = "DELETE FROM users_blob "; $sql .= " WHERE id = ?"; $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($row['id'])); } _error_log("Id for table users_blob not defined for deletion"); return false; } public function getDonationLink() { return $this->donationLink; } public function getDonationLinkIfEnabled() { global $advancedCustomUser; if ($advancedCustomUser->allowDonationLink) { return $this->donationLink; } return false; } public function setDonationLink($donationLink) { $this->donationLink = $donationLink; } public static function donationLink() { if (self::isLogged()) { return $_SESSION['user']['donationLink']; } else { return false; } } public static function loginFromRequest() { $inputJSON = url_get_contents('php://input'); $input = _json_decode($inputJSON, true); //convert JSON into array if (is_array($input)) { foreach ($input as $key => $value) { if (empty($_REQUEST[$key])) { $_REQUEST[$key] = $value; } } } if (!empty($_REQUEST['do_not_login'])) { return false; } if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { $user = new User(0, $_REQUEST['user'], $_REQUEST['pass']); $user->login(false, !empty($_REQUEST['encodedPass'])); } } public static function loginFromRequestToGet() { if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { $return = "user={$_REQUEST['user']}&pass={$_REQUEST['pass']}"; if (!empty($_REQUEST['encodedPass'])) { $return .= "&encodedPass=" . intval($_REQUEST['encodedPass']); } return $return; } return ""; } public static function getBlockUserButton($users_id) { $canBlock = self::userCanBlockUserWithReason($users_id); if (!$canBlock->result) { return ""; } return ReportVideo::buttonBlockUser($users_id); } public static function getActionBlockUserButton($users_id) { $canBlock = self::userCanBlockUserWithReason($users_id); if (!$canBlock->result) { return ""; } return ReportVideo::actionButtonBlockUser($users_id); } public static function userCanBlockUser($users_id, $ignoreIfIsAlreadyBLocked = false) { if (empty($users_id)) { return false; } if (!User::isLogged()) { return false; } if ($users_id == User::getId()) { return false; } if (empty($ignoreIfIsAlreadyBLocked)) { $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { return false; } } return true; } public static function userCanBlockUserWithReason($users_id, $ignoreIfIsAlreadyBLocked = false) { $obj = new stdClass(); $obj->result = false; $obj->msg = "Unkonw"; if (empty($users_id)) { $obj->msg = "Empty User ID"; return $obj; } if (!User::isLogged()) { $obj->msg = "You are not logged"; return $obj; } if ($users_id == User::getId()) { $obj->msg = "You cannot block your own video"; return $obj; } if (empty($ignoreIfIsAlreadyBLocked)) { $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { $obj->msg = "this user is already blocked"; return $obj; } } $obj->result = true; $obj->msg = "You can block"; return $obj; } public static function hasBlockedUser($reported_users_id, $users_id = 0) { if (empty($users_id)) { $users_id = User::getId(); } if (!self::userCanBlockUser($reported_users_id, true)) { return false; } $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (!empty($report)) { return ReportVideo::isBlocked($reported_users_id, $users_id); } else { return false; } } public function updateUserImages($params = array()) { $id = $this->id; $obj = new stdClass(); // Update Background Image if (isset($params['backgroundImg']) && $params['backgroundImg'] != '') { $background = url_get_contents($params['backgroundImg']); $ext = pathinfo(parse_url($params['backgroundImg'], PHP_URL_PATH), PATHINFO_EXTENSION); $allowed = array('jpg', 'jpeg', 'gif', 'png'); if (!in_array(strtolower($ext), $allowed)) { return "File extension error background Image, We allow only (" . implode(",", $allowed) . ")"; } $backgroundPath = "videos/userPhoto/tmp_background{$id}." . $ext; $oldfile = "videos/userPhoto/background{$id}.png"; $file = "videos/userPhoto/background{$id}.jpg"; if (!isset($global['systemRootPath'])) { $global['systemRootPath'] = '../../'; } $filePath = $global['systemRootPath'] . $backgroundPath; $updateBackground = file_put_contents($filePath, $background); convertImage($filePath, $global['systemRootPath'] . $file, 70); if (file_exists($filePath)) { unlink($filePath); } if (file_exists($oldfile)) { unlink($oldfile); } if ($updateBackground) { $obj->background = 'Background has been updated!'; } else { $obj->background = 'Error updating background.'; } $this->setBackgroundURL($file); } // Update Profile Image if (isset($params['profileImg']) && $params['profileImg'] != '') { $photo = url_get_contents($params['profileImg']); $photoPath = "videos/userPhoto/photo{$id}.png"; if (!isset($global['systemRootPath'])) { $global['systemRootPath'] = '../../'; } $filePath = $global['systemRootPath'] . $photoPath; if (file_exists($filePath)) { unlink($filePath); } $updateProfile = file_put_contents($filePath, $photo); if ($updateProfile) { $obj->profile = 'Profile has been updated!'; } else { $obj->profile = 'Error updating profile.'; } $this->setPhotoURL($photoPath); } $formats = "ssi"; $values[] = $this->photoURL; $values[] = $this->backgroundURL; $values[] = $this->id; $sql = "UPDATE users SET " . "photoURL = ?, backgroundURL = ?, " . " modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, $formats, $values); $obj->save = $insert_row; // create/update data for photoURL / backgroundURL return $obj; } function getExtra_info() { return $this->extra_info; } function setExtra_info($extra_info) { $this->extra_info = $extra_info; } static function saveExtraInfo($string, $users_id) { $sql = "UPDATE users SET " . "extra_info = ?, " . " modified = now() WHERE id = ?"; return sqlDAL::writeSql($sql, "si", array($string, $users_id)); } + + static function userGroupsMatch($user_groups, $users_id=0){ + if(empty($users_id)){ + $users_id = User::getId(); + } + if(empty($user_groups)){ + return true; + } + if(empty($users_id)){ + return false; + } + if(!is_array($user_groups)){ + $user_groups = array($user_groups); + } + $user_users_groups = UserGroups::getUserGroups($users_id); + if(empty($user_users_groups)){ + return false; + } + foreach ($user_users_groups as $value) { + if(in_array($value['id'], $user_groups)){ + return true; + } + } + return false; + } } diff --git a/objects/video.php b/objects/video.php index d63039e11..59d7c2534 100644 --- a/objects/video.php +++ b/objects/video.php @@ -1,4130 +1,4014 @@ 'active', - 'k' => 'active and encoding', - 'i' => 'inactive', - 'e' => 'encoding', - 'x' => 'encoding error', - 'd' => 'downloading', - 'xmp4' => 'encoding mp4 error', - 'xwebm' => 'encoding webm error', - 'xmp3' => 'encoding mp3 error', - 'xogg' => 'encoding ogg error', - 'ximg' => 'get image error', - 't' => 'transfering'); + 'a' => 'Active', + 'k' => 'Active and Encoding', + 'i' => 'Inactive', + 'e' => 'Encoding', + 'x' => 'Encoding Error', + 'd' => 'Downloading', + 't' => 'Transfering', + 'u' => 'Unlisted'); + public static $statusActive = 'a'; + public static $statusActiveAndEncoding = 'k'; + public static $statusInactive = 'i'; + public static $statusEncoding = 'e'; + public static $statusEncodingError = 'x'; + public static $statusDownloading = 'd'; + public static $statusTranfering = 't'; + public static $statusUnlisted = 'u'; + public static $rratingOptions = array('', 'g', 'pg', 'pg-13', 'r', 'nc-17', 'ma'); //ver 3.4 private $youtubeId; public static $typeOptions = array('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie', 'image', 'zip', 'notfound', 'blockedUser'); public function __construct($title = "", $filename = "", $id = 0) { global $global; $this->rotation = 0; $this->zoom = 1; if (!empty($id)) { $this->load($id); } if (!empty($title)) { $this->setTitle($title); } if (!empty($filename)) { $this->filename = $filename; } } public function addView($currentTime = 0) { global $global; if (empty($this->id)) { return false; } $sql = "UPDATE videos SET views_count = views_count+1, modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); if ($insert_row) { $obj = new stdClass(); $obj->videos_statistics_id = VideoStatistic::create($this->id, $currentTime); $obj->videos_id = $this->id; $this->views_count++; AVideoPlugin::addView($this->id, $this->views_count); return $obj; } die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } public function updateViewsCount($total) { global $global; if (empty($this->id)) { return false; } $total = intval($total); if ($total < 0) { return false; } $sql = "UPDATE videos SET views_count = {$total}, modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); if ($insert_row) { return $insert_row; } die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } public function addViewPercent($percent = 25) { global $global; if (empty($this->id)) { return false; } $sql = "UPDATE videos SET views_count_{$percent} = IFNULL(views_count_{$percent}, 0)+1, modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); if ($insert_row) { return true; } die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } // allow users to count a view again in case it is refreshed public static function unsetAddView($videos_id) { // allow users to count a view again in case it is refreshed if (!empty($_SESSION['addViewCount'][$videos_id]['time']) && $_SESSION['addViewCount'][$videos_id]['time'] <= time()) { _session_start(); unset($_SESSION['addViewCount'][$videos_id]); } } public function load($id) { $video = self::getVideoLight($id); if (empty($video)) { return false; } foreach ($video as $key => $value) { $this->$key = $value; } } function getLive_transmitions_history_id() { return $this->live_transmitions_history_id; } function setLive_transmitions_history_id($live_transmitions_history_id) { AVideoPlugin::onVideoSetLive_transmitions_history_id($this->id, $this->live_transmitions_history_id, intval($live_transmitions_history_id)); $this->live_transmitions_history_id = intval($live_transmitions_history_id); } public function getEncoderURL() { return $this->encoderURL; } public function getFilepath() { return $this->filepath; } public function getFilesize() { return intval($this->filesize); } public function setEncoderURL($encoderURL) { if (filter_var($encoderURL, FILTER_VALIDATE_URL) !== false) { AVideoPlugin::onVideoSetEncoderURL($this->id, $this->encoderURL, $encoderURL); $this->encoderURL = $encoderURL; } } public function setFilepath($filepath) { AVideoPlugin::onVideoSetFilepath($this->id, $this->filepath, $filepath); $this->filepath = $filepath; } public function setFilesize($filesize) { AVideoPlugin::onVideoSetFilesize($this->id, $this->filesize, $filesize); $this->filesize = intval($filesize); } public function setUsers_id($users_id) { AVideoPlugin::onVideoSetUsers_id($this->id, $this->users_id, $users_id); $this->users_id = $users_id; } public function getSites_id() { return $this->sites_id; } public function setSites_id($sites_id) { AVideoPlugin::onVideoSetSites_id($this->id, $this->sites_id, $sites_id); $this->sites_id = $sites_id; } public function getVideo_password() { return trim($this->video_password); } public function setVideo_password($video_password) { AVideoPlugin::onVideoSetVideo_password($this->id, $this->video_password, $video_password); $this->video_password = trim($video_password); } public function save($updateVideoGroups = false, $allowOfflineUser = false) { global $advancedCustom; global $global; if (!User::isLogged() && !$allowOfflineUser) { _error_log('Video::save permission denied to save'); return false; } if (empty($this->title)) { $this->title = uniqid(); } $this->clean_title = substr($this->clean_title, 0, 187); if (empty($this->clean_title)) { $this->setClean_title($this->title); } $this->clean_title = self::fixCleanTitle($this->clean_title, 1, $this->id); if (empty($this->status)) { $this->status = 'e'; } if (empty($this->type) || !in_array($this->type, self::$typeOptions)) { $this->type = 'video'; } if (empty($this->isSuggested)) { $this->isSuggested = 0; } else { $this->isSuggested = 1; } if (empty($this->categories_id)) { $p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory"); $category = Category::getCategoryDefault(); $categories_id = $category['id']; if (empty($categories_id)) { $categories_id = 'NULL'; } if ($p) { $this->categories_id = $p->getCategoryId(); } else { $this->categories_id = $categories_id; } if (empty($this->categories_id)) { $this->categories_id = $categories_id; } } // check if category exists $cat = new Category($this->categories_id); if (empty($cat->getName())) { $catDefault = Category::getCategoryDefault(); $this->categories_id = $catDefault['id']; } $this->setTitle($global['mysqli']->real_escape_string(trim($this->title))); $this->description = ($global['mysqli']->real_escape_string($this->description)); if (forbiddenWords($this->title) || forbiddenWords($this->description)) { return false; } if (empty($this->users_id)) { $this->users_id = User::getId(); } $this->next_videos_id = intval($this->next_videos_id); if (empty($this->next_videos_id)) { $this->next_videos_id = 'NULL'; } $this->sites_id = intval($this->sites_id); if (empty($this->sites_id)) { $this->sites_id = 'NULL'; } $this->serie_playlists_id = intval($this->serie_playlists_id); if (empty($this->serie_playlists_id)) { $this->serie_playlists_id = 'NULL'; } if (empty($this->filename)) { $this->filename = $this->type . "_" . uniqid(); } $this->can_download = intval($this->can_download); $this->can_share = intval($this->can_share); $this->only_for_paid = intval($this->only_for_paid); $this->filesize = intval($this->filesize); $this->rate = floatval($this->rate); if (!filter_var($this->videoLink, FILTER_VALIDATE_URL)) { $this->videoLink = ''; if ($this->type == 'embed') { $this->type = 'video'; } } if (empty($this->live_transmitions_history_id)) { $this->live_transmitions_history_id = 'NULL'; } if (!empty($this->id)) { if (!$this->userCanManageVideo() && !$allowOfflineUser && !Permissions::canModerateVideos()) { header('Content-Type: application/json'); die('{"error":"3 ' . __("Permission denied") . '"}'); } $sql = "UPDATE videos SET title = '{$this->title}',clean_title = '{$this->clean_title}'," . " filename = '{$this->filename}', categories_id = '{$this->categories_id}', status = '{$this->status}'," . " description = '{$this->description}', duration = '{$this->duration}', type = '{$this->type}', videoDownloadedLink = '{$this->videoDownloadedLink}', youtubeId = '{$this->youtubeId}', videoLink = '{$this->videoLink}', next_videos_id = {$this->next_videos_id}, isSuggested = {$this->isSuggested}, users_id = {$this->users_id}, " . " trailer1 = '{$this->trailer1}', trailer2 = '{$this->trailer2}', trailer3 = '{$this->trailer3}', rate = '{$this->rate}', can_download = '{$this->can_download}', can_share = '{$this->can_share}', only_for_paid = '{$this->only_for_paid}', rrating = '{$this->rrating}', externalOptions = '{$this->externalOptions}', sites_id = {$this->sites_id}, serie_playlists_id = {$this->serie_playlists_id} ,live_transmitions_history_id = {$this->live_transmitions_history_id} , video_password = '{$this->video_password}', " . " encoderURL = '{$this->encoderURL}', filepath = '{$this->filepath}' , filesize = '{$this->filesize}' , modified = now()" . " WHERE id = {$this->id}"; + + $saved = sqlDAL::writeSql($sql); + if($saved){ + $insert_row = $this->id; + } } else { $sql = "INSERT INTO videos " . "(title,clean_title, filename, users_id, categories_id, status, description, duration,type,videoDownloadedLink, next_videos_id, created, modified, videoLink, can_download, can_share, only_for_paid, rrating, externalOptions, sites_id, serie_playlists_id,live_transmitions_history_id, video_password, encoderURL, filepath , filesize) values " . "('{$this->title}','{$this->clean_title}', '{$this->filename}', {$this->users_id},{$this->categories_id}, '{$this->status}', '{$this->description}', '{$this->duration}', '{$this->type}', '{$this->videoDownloadedLink}', {$this->next_videos_id},now(), now(), '{$this->videoLink}', '{$this->can_download}', '{$this->can_share}','{$this->only_for_paid}', '{$this->rrating}', '$this->externalOptions', {$this->sites_id}, {$this->serie_playlists_id},{$this->live_transmitions_history_id}, '{$this->video_password}', '{$this->encoderURL}', '{$this->filepath}', '{$this->filesize}')"; + + $insert_row = sqlDAL::writeSql($sql); } - $insert_row = sqlDAL::writeSql($sql); if ($insert_row) { _error_log("Video::save ({$this->title}) Saved id = {$insert_row} "); Category::clearCacheCount(); if (empty($this->id)) { $id = $global['mysqli']->insert_id; $this->id = $id; // check if needs to add the video in a user group $p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory"); if ($p) { $updateVideoGroups = true; $this->videoGroups = $p->getUserGroupsArray(); } } else { $id = $this->id; } ObjectYPT::deleteCache("getItemprop{$this->id}"); ObjectYPT::deleteCache("getLdJson{$this->id}"); ObjectYPT::deleteCache("getVideoTags{$this->id}"); self::deleteTagsAsync($this->id); if ($updateVideoGroups) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; // update the user groups UserGroups::updateVideoGroups($id, $this->videoGroups); } // I am not sure what is it for //Video::autosetCategoryType($id); if (!empty($this->old_categories_id)) { //Video::autosetCategoryType($this->old_categories_id); } self::clearCache($this->id); return $id; } _error_log('Video::save ' . $sql . ' Save Video Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql"); return false; } - /* - static function autosetCategoryType($catId) { - global $global, $config; - if ($config->currentVersionLowerThen('5.01')) { - return false; - } - $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; - - $res = sqlDAL::readSql($sql, "i", array($catId)); - $catTypeCache = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - - $videoFound = false; - $audioFound = false; - if ($catTypeCache) { - // 3 means auto - if ($catTypeCache['manualSet'] == "0") { - // start incremental search and save - $sql = "SELECT * FROM `videos` WHERE categories_id = ?"; - $res = sqlDAL::readSql($sql, "i", array($catId)); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - foreach ($fullResult as $row) { - - if ($row['type'] == "audio") { - // echo "found audio"; - $audioFound = true; - } else if ($row['type'] == "video") { - //echo "found video"; - $videoFound = true; - } - } - } - - if (($videoFound == false) || ($audioFound == false)) { - $sql = "SELECT * FROM `categories` WHERE parentId = ?"; - $res = sqlDAL::readSql($sql, "i", array($catId)); - $fullResult = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - //$tmpVid = $res->fetch_assoc(); - foreach ($fullResult as $row) { - $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; - $res = sqlDAL::readSql($sql, "i", array($row['parentId'])); - $fullResult2 = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - foreach ($fullResult2 as $row) { - if ($row['type'] == "audio") { - // echo "found audio"; - $audioFound = true; - } else if ($row['type'] == "video") { - //echo "found video"; - $videoFound = true; - } - } - } - } - } - $sql = "UPDATE `category_type_cache` SET `type` = '"; - if (($videoFound) && ($audioFound)) { - $sql .= "0"; - } else if ($audioFound) { - $sql .= "1"; - } else if ($videoFound) { - $sql .= "2"; - } else { - $sql .= "0"; - } - $sql .= "' WHERE `category_type_cache`.`categoryId` = ?;"; - sqlDAL::writeSql($sql, "i", array($catId)); - } - } else { - // start incremental search and save - and a lot of this redundant stuff in a method.. - $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; - $res = sqlDAL::readSql($sql, "i", array($catId)); - $fullResult2 = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - foreach ($fullResult2 as $row) { - if ($row['type'] == "audio") { - $audioFound = true; - } else if ($row['type'] == "video") { - $videoFound = true; - } - } - } - if (($videoFound == false) || ($audioFound == false)) { - $sql = "SELECT parentId FROM `categories` WHERE parentId = ?;"; - $res = sqlDAL::readSql($sql, "i", array($catId)); - $fullResult2 = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - foreach ($fullResult2 as $cat) { - $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; - $res = sqlDAL::readSql($sql, "i", array($cat['parentId'])); - $fullResult2 = sqlDAL::fetchAllAssoc($res); - sqlDAL::close($res); - if ($res != false) { - foreach ($fullResult2 as $row) { - if ($row['type'] == "audio") { - $audioFound = true; - } else if ($row['type'] == "video") { - $videoFound = true; - } - } - } - } - } - } - $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; - $res = sqlDAL::readSql($sql, "i", array($catId)); - $exist = sqlDAL::fetchAssoc($res); - sqlDAL::close($res); - $sqlType = 99; - if (($videoFound) && ($audioFound)) { - $sqlType = 0; - } else if ($audioFound) { - $sqlType = 1; - } else if ($videoFound) { - $sqlType = 2; - } - $values = array(); - if (empty($exist)) { - $sql = "INSERT INTO `category_type_cache` (`categoryId`, `type`) VALUES (?, ?);"; - $values = array($catId, $sqlType); - } else { - $sql = "UPDATE `category_type_cache` SET `type` = ? WHERE `category_type_cache`.`categoryId` = ?;"; - $values = array($sqlType, $catId); - } - sqlDAL::writeSql($sql, "ii", $values); - } - } - */ - // i would like to simplify the big part of the method above in this method, but won't work as i want. public static function internalAutoset($catId, $videoFound, $audioFound) { global $config; if ($config->currentVersionLowerThen('5.01')) { return false; } $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { $audioFound = true; } elseif ($row['type'] == "video") { $videoFound = true; } } } if (($videoFound == false) || ($audioFound == false)) { $sql = "SELECT parentId,categories_id FROM `categories` WHERE parentId = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $cat) { $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($cat['parentId'])); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult as $row) { if ($row['type'] == 'audio') { $audioFound = true; } elseif ($row['type'] == 'video') { $videoFound = true; } } } } } } return array($videoFound, audioFound); } public function setClean_title($clean_title) { if (preg_match("/video-automatically-booked/i", $clean_title) && !empty($this->clean_title)) { return false; } $clean_title = cleanURLName($clean_title); AVideoPlugin::onVideoSetClean_title($this->id, $this->clean_title, $clean_title); $this->clean_title = $clean_title; } public function setDuration($duration) { AVideoPlugin::onVideoSetDuration($this->id, $this->duration, $duration); $this->duration = $duration; } public function getDuration() { return $this->duration; } public function getIsSuggested() { return $this->isSuggested; } public function setIsSuggested($isSuggested) { if (empty($isSuggested) || $isSuggested === "false") { $new_isSuggested = 0; } else { $new_isSuggested = 1; } AVideoPlugin::onVideoSetIsSuggested($this->id, $this->isSuggested, $new_isSuggested); $this->isSuggested = $new_isSuggested; } public function setStatus($status) { if (!empty($this->id)) { global $global; + + if(empty(Video::$statusDesc[$status])){ + _error_log("Video::setStatus({$status}) NOT found ", AVideoLog::$WARNING); + return false; + } + _error_log("Video::setStatus({$status}) ".json_encode(debug_backtrace()), AVideoLog::$WARNING); $sql = "UPDATE videos SET status = ?, modified = now() WHERE id = ? "; $res = sqlDAL::writeSql($sql, 'si', array($status, $this->id)); if ($global['mysqli']->errno != 0) { die('Error on update Status: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } self::deleteTagsAsync($this->id); } AVideoPlugin::onVideoSetStatus($this->id, $this->status, $status); $this->status = $status; + return $status; + } + + public function setAutoStatus($default = 'a') { + global $advancedCustom; + if (empty($advancedCustom)) { + $advancedCustom = AVideoPlugin::getDataObject('CustomizeAdvanced'); + } + + if (!empty($_POST['fail'])) { + return $this->setStatus(Video::$statusEncodingError); + } else { + if (!empty($_REQUEST['overrideStatus'])) { + return $this->setStatus($_REQUEST['overrideStatus']); + } else { // encoder did not provide a status + if (!empty($_REQUEST['keepEncoding'])) { + return $this->setStatus(Video::$statusActiveAndEncoding); + } else{ + if($this->getTitle() !== "Video automatically booked"){ + if (!empty($advancedCustom->makeVideosInactiveAfterEncode)) { + return $this->setStatus(Video::$statusInactive); + } elseif (!empty($advancedCustom->makeVideosUnlistedAfterEncode)) { + return $this->setStatus(Video::$statusUnlisted); + } + }else{ + return $this->setStatus(Video::$statusInactive); + } + } + } + } + return $this->setStatus($default); } public function setType($type, $force = true) { if ($force || empty($this->type)) { AVideoPlugin::onVideoSetType($this->id, $this->type, $type, $force); $this->type = $type; } } public function setRotation($rotation) { $saneRotation = intval($rotation) % 360; AVideoPlugin::onVideoSetRotation($this->id, $this->rotation, $saneRotation); if (!empty($this->id)) { global $global; $sql = "UPDATE videos SET rotation = '{$saneRotation}', modified = now() WHERE id = {$this->id} "; $res = sqlDAL::writeSql($sql); if ($global['mysqli']->errno != 0) { die('Error on update Rotation: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } $this->rotation = $saneRotation; } public function getRotation() { return $this->rotation; } public function getUsers_id() { return $this->users_id; } public function setZoom($zoom) { $saneZoom = abs(floatval($zoom)); if ($saneZoom < 0.1 || $saneZoom > 10) { die('Zoom level must be between 0.1 and 10'); } if (!empty($this->id)) { global $global; $sql = "UPDATE videos SET zoom = '{$saneZoom}', modified = now() WHERE id = {$this->id} "; $res = sqlDAL::writeSql($sql); if ($global['mysqli']->errno != 0) { die('Error on update Zoom: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } AVideoPlugin::onVideoSetZoom($this->id, $this->zoom, $saneZoom); $this->zoom = $saneZoom; } public function getZoom() { return $this->zoom; } public static function getUserGroupsCanSeeSQL($tableAlias = '') { global $global; if (Permissions::canModerateVideos()) { return ""; } - + $obj = AVideoPlugin::getDataObject('Subscription'); if ($obj && $obj->allowFreePlayWithAds) { $sql = " AND {$tableAlias}only_for_paid = 0 "; return $sql; - }else{ + } else { $sql = " (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0 "; if (User::isLogged()) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; $userGroups = UserGroups::getUserGroups(User::getId()); $groups_id = array(); foreach ($userGroups as $value) { $groups_id[] = $value['id']; } if (!empty($groups_id)) { $sql = " (({$sql}) OR ((SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id AND users_groups_id IN ('" . implode("','", $groups_id) . "') ) > 0)) "; } } return " AND " . $sql; } } public static function getVideo($id = "", $status = "viewable", $ignoreGroup = false, $random = false, $suggestedOnly = false, $showUnlisted = false, $ignoreTags = false, $activeUsersOnly = true) { global $global, $config, $advancedCustom, $advancedCustomUser; if ($config->currentVersionLowerThen('5')) { return false; } $status = str_replace("'", "", $status); $id = intval($id); if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); } } _mysql_connect(); $sql = "SELECT u.*, v.*, " . " nv.title as next_title," . " nv.clean_title as next_clean_title," . " nv.filename as next_filename," . " nv.id as next_id," . " c.id as category_id,c.iconClass,c.name as category,c.iconClass, c.clean_name as clean_category,c.description as category_description,c.nextVideoOrder as category_order, v.created as videoCreation, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes "; if (User::isLogged()) { $sql .= ", (SELECT `like` FROM likes as l where l.videos_id = v.id AND users_id = '" . User::getId() . "' ) as myVote "; } else { $sql .= ", 0 as myVote "; } $sql .= " FROM videos as v " . "LEFT JOIN categories c ON categories_id = c.id " . "LEFT JOIN users u ON v.users_id = u.id " . "LEFT JOIN videos nv ON v.next_videos_id = nv.id " . " WHERE 1=1 "; if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } if (!empty($id)) { $sql .= " AND v.id = '$id' "; } $sql .= AVideoPlugin::getVideoWhereClause(); $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL('v.'); } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } elseif ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if (!empty($videosArrayId) && is_array($videosArrayId)) { $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; } if ($status == "viewable") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if (!empty($_GET['catName'])) { $catName = $global['mysqli']->real_escape_string($_GET['catName']); $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))"; } if (empty($id) && !empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); if (!empty($user['id'])) { $sql .= " AND v.users_id = '{$user['id']}' "; } } if (!empty($_GET['search'])) { $_POST['searchPhrase'] = $_GET['search']; } if (!empty($_POST['searchPhrase'])) { $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description'); - if($advancedCustomUser->videosSearchAlsoSearchesOnChannelName){ + if ($advancedCustomUser->videosSearchAlsoSearchesOnChannelName) { $searchFieldsNames[] = 'u.channelName'; } if (AVideoPlugin::isEnabledByName("VideoTags")) { $sql .= " AND ("; $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; $sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames, "OR"); $searchFieldsNames = array('v.title'); $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']); $sql .= ")"; } else { $sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames); $searchFieldsNames = array('v.title'); $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']) . ')'; } } if (!$ignoreGroup) { $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } } // replace random based on this $firstClauseLimit = ""; if (empty($id)) { if (empty($random) && !empty($_GET['videoName'])) { $sql .= " AND v.clean_title = '{$_GET['videoName']}' "; } elseif (!empty($random)) { $sql .= " AND v.id != {$random} "; $rand = rand(0, self::getTotalVideos($status, false, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly)); $rand = ($rand - 2) < 0 ? 0 : $rand - 2; $firstClauseLimit = "$rand, "; //$sql .= " ORDER BY RAND() "; } elseif ($suggestedOnly && empty($_GET['videoName']) && empty($_GET['search']) && empty($_GET['searchPhrase'])) { $sql .= " AND v.isSuggested = 1 "; $rand = rand(0, self::getTotalVideos($status, false, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly)); $rand = ($rand - 2) < 0 ? 0 : $rand - 2; $firstClauseLimit = "$rand, "; //$sql .= " ORDER BY RAND() "; } elseif (!empty($_GET['v']) && is_numeric($_GET['v'])) { $vid = intval($_GET['v']); $sql .= " AND v.id = {$vid} "; } else { $sql .= " ORDER BY v.Created DESC "; } } if (strpos($sql, 'v.id IN') === false && strpos(strtolower($sql), 'limit') === false) { $sql .= " LIMIT {$firstClauseLimit}1"; } //echo $sql, "
";//exit; $res = sqlDAL::readSql($sql); $video = sqlDAL::fetchAssoc($res); // if there is a search, and there is no data and is inside a channel try again without a channel if (!empty($_GET['search']) && empty($video) && !empty($_GET['channelName'])) { $channelName = $_GET['channelName']; unset($_GET['channelName']); $return = self::getVideo($id, $status, $ignoreGroup, $random, $suggestedOnly, $showUnlisted, $ignoreTags, $activeUsersOnly); $_GET['channelName'] = $channelName; return $return; } sqlDAL::close($res); if ($res != false) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; if (!empty($video)) { $video = cleanUpRowFromDatabase($video); $video['category'] = xss_esc_back($video['category']); $video['groups'] = UserGroups::getVideoGroups($video['id']); $video['title'] = UTF8encode($video['title']); $video['description'] = UTF8encode($video['description']); $video['progress'] = self::getVideoPogressPercent($video['id']); $video['isFavorite'] = self::isFavorite($video['id']); $video['isWatchLater'] = self::isWatchLater($video['id']); $video['favoriteId'] = self::getFavoriteIdFromUser(User::getId()); $video['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId()); if (empty($video['filesize']) && ($video['type'] == "video" || $video['type'] == "audio")) { $video['filesize'] = Video::updateFilesize($video['id']); } if (!$ignoreTags) { $video['tags'] = self::getTags($video['id']); } if (!empty($video['externalOptions'])) { $video['externalOptions'] = _json_decode($video['externalOptions']); } else { $video['externalOptions'] = new stdClass(); } $video['descriptionHTML'] = strip_tags($video['description']) === $video['description'] ? nl2br(textToLink(htmlentities($video['description']))) : $video['description']; if (!$ignoreTags && AVideoPlugin::isEnabledByName("VideoTags")) { $video['videoTags'] = Tags::getAllFromVideosId($video['id']); $video['videoTagsObject'] = Tags::getObjectFromVideosId($video['id']); } } } else { $video = false; } return $video; } public static function getVideoLight($id) { global $global, $config; $id = intval($id); $sql = "SELECT * FROM videos WHERE id = '$id' LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } public static function getTotalVideosSizeFromUser($users_id) { global $global, $config; $users_id = intval($users_id); $sql = "SELECT sum(filesize) as total FROM videos WHERE 1=1 "; if (!empty($users_id)) { $sql .= " AND users_id = '$users_id'"; } $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return intval($video['total']); } public static function getTotalVideosFromUser($users_id) { global $global, $config; $users_id = intval($users_id); $sql = "SELECT count(*) as total FROM videos WHERE 1=1 "; if (!empty($users_id)) { $sql .= " AND users_id = '$users_id'"; } $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return intval($video['total']); } public static function getVideoFromFileName($fileName, $ignoreGroup = false, $ignoreTags = false) { global $global; if (empty($fileName)) { return false; } $parts = explode("/", $fileName); if (!empty($parts[0])) { $fileName = $parts[0]; } $fileName = self::getCleanFilenameFromFile($fileName); $sql = "SELECT id FROM videos WHERE filename = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($fileName)); if ($res != false) { $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($video['id'])) { return self::getVideo($video['id'], "", $ignoreGroup, false, false, true, $ignoreTags); } } return false; } public static function getVideoFromFileNameLight($fileName) { global $global; $fileName = self::getCleanFilenameFromFile($fileName); if (empty($fileName)) { return false; } $sql = "SELECT * FROM videos WHERE filename = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($fileName), true); if ($res != false) { $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } return false; } public static function getVideoFromCleanTitle($clean_title) { // even increasing the max_allowed_packet it only goes away when close and reopen the connection global $global; $sql = "SELECT id FROM videos WHERE clean_title = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($clean_title)); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($video) && $res) { return self::getVideo($video['id'], "", true, false, false, true); //$video['groups'] = UserGroups::getVideoGroups($video['id']); } else { return false; } } /** * * @global type $global * @param type $status * @param type $showOnlyLoggedUserVideos you may pass an user ID to filter results * @param type $ignoreGroup * @param type $videosArrayId an array with videos to return (for filter only) * @return boolean */ public static function getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false, $is_serie = null) { global $global, $config, $advancedCustom, $advancedCustomUser; if ($config->currentVersionLowerThen('5')) { return false; } if (!empty($_POST['sort']['suggested'])) { $suggestedOnly = true; } if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})"); $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__); } } $status = str_replace("'", "", $status); $sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes " . " FROM videos as v " . " LEFT JOIN categories c ON categories_id = c.id " . " LEFT JOIN users u ON v.users_id = u.id " . " WHERE 2=2 "; $blockedUsers = self::getBlockedUsersIdsArray(); if (!empty($blockedUsers)) { $sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') "; } if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $uid = intval(User::getId()); $sql .= " AND v.users_id = '{$uid}'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $uid = intval($showOnlyLoggedUserVideos); $sql .= " AND v.users_id = '{$uid}'"; } elseif (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $uid = intval($user['id']); $sql .= " AND v.users_id = '{$uid}' "; } if (isset($_REQUEST['is_serie']) && empty($is_serie)) { $is_serie = intval($_REQUEST['is_serie']); } if (isset($is_serie)) { if (empty($is_serie)) { $sql .= " AND v.serie_playlists_id IS NULL "; } else { $sql .= " AND v.serie_playlists_id IS NOT NULL "; } } if (!empty($videosArrayId) && is_array($videosArrayId)) { $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; } if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { TimeLogStart("video::getAllVideos::getAllVideosExcludeVideosIDArray"); $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } TimeLogEnd("video::getAllVideos::getAllVideosExcludeVideosIDArray", __LINE__); } if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL('v.'); } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } elseif ($_SESSION['type'] == 'videoOnly') { $sql .= " AND (v.type = 'video')"; } elseif ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif ($status == "publicOnly") { $sql .= " AND v.status IN ('a', 'k') AND (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if (!empty($_GET['catName'])) { $catName = $global['mysqli']->real_escape_string($_GET['catName']); $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))"; } if (!empty($_GET['search'])) { $_POST['searchPhrase'] = $_GET['search']; } if (!empty($_GET['modified'])) { $_GET['modified'] = str_replace("'", "", $_GET['modified']); $sql .= " AND v.modified >= '{$_GET['modified']}'"; } if (!empty($_POST['searchPhrase'])) { $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description'); - if($advancedCustomUser->videosSearchAlsoSearchesOnChannelName){ + if ($advancedCustomUser->videosSearchAlsoSearchesOnChannelName) { $searchFieldsNames[] = 'u.channelName'; } if (AVideoPlugin::isEnabledByName("VideoTags")) { $sql .= " AND ("; $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; $sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames, "OR"); $searchFieldsNames = array('v.title'); $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']); $sql .= ")"; } else { $sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames); $searchFieldsNames = array('v.title'); $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']) . ')'; } } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; $sql .= " ORDER BY RAND() "; $sort = @$_POST['sort']; unset($_POST['sort']); $sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true); if (strpos(strtolower($sql), 'limit') === false) { $sql .= " LIMIT 60 "; } $_POST['sort'] = $sort; } elseif (!isset($_POST['sort']['trending']) && !isset($_GET['sort']['trending'])) { if (!empty($_POST['sort']['created']) && !empty($_POST['sort']['likes'])) { $_POST['sort']['v.created'] = $_POST['sort']['created']; unset($_POST['sort']['created']); } $sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true); } else { unset($_POST['sort']['trending']); unset($_GET['sort']['trending']); $rows = array(); if (!empty($_REQUEST['current']) && $_REQUEST['current'] == 1) { $rows = VideoStatistic::getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly); } $ids = array(); foreach ($rows as $row) { $ids[] = $row['id']; } if (!empty($ids)) { $sql .= " ORDER BY FIND_IN_SET(v.id, '" . implode(",", $ids) . "') DESC, likes DESC "; } else { $sql .= " ORDER BY likes DESC "; } $sql .= ObjectYPT::getSqlLimit(); } if (strpos(strtolower($sql), 'limit') === false) { if (!empty($_GET['limitOnceToOne'])) { $sql .= " LIMIT 1"; unset($_GET['limitOnceToOne']); } else { $_REQUEST['rowCount'] = getRowCount(); if (!empty($_REQUEST['rowCount'])) { $sql .= " LIMIT {$_REQUEST['rowCount']}"; } else { _error_log("getAllVideos without limit " . json_encode(debug_backtrace())); if (empty($global['limitForUnlimitedVideos'])) { $global['limitForUnlimitedVideos'] = 100; } if ($global['limitForUnlimitedVideos'] > 0) { $sql .= " LIMIT {$global['limitForUnlimitedVideos']}"; } } } } //echo $sql;//exit; //_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); // if there is a search, and there is no data and is inside a channel try again without a channel if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) { $channelName = $_GET['channelName']; unset($_GET['channelName']); $return = self::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly, $suggestedOnly); $_GET['channelName'] = $channelName; return $return; } sqlDAL::close($res); $videos = array(); if ($res != false) { require_once 'userGroups.php'; TimeLogStart("video::getAllVideos foreach"); foreach ($fullData as $row) { $row = cleanUpRowFromDatabase($row); if (!self::canEdit($row['id'])) { if (!empty($row['video_password'])) { $row['video_password'] = 1; } else { $row['video_password'] = 0; } } if ($getStatistcs) { TimeLogStart("video::getAllVideos getStatistcs"); $previewsMonth = date("Y-m-d 00:00:00", strtotime("-30 days")); $previewsWeek = date("Y-m-d 00:00:00", strtotime("-7 days")); $today = date('Y-m-d 23:59:59'); $row['statistc_all'] = VideoStatistic::getStatisticTotalViews($row['id']); $row['statistc_today'] = VideoStatistic::getStatisticTotalViews($row['id'], false, date('Y-m-d 00:00:00'), $today); $row['statistc_week'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsWeek, $today); $row['statistc_month'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsMonth, $today); $row['statistc_unique_user'] = VideoStatistic::getStatisticTotalViews($row['id'], true); TimeLogEnd("video::getAllVideos getStatistcs", __LINE__, 0.5); } TimeLogStart("video::getAllVideos otherInfo"); $otherInfocachename = "otherInfo{$row['id']}"; $otherInfo = object_to_array(ObjectYPT::getCache($otherInfocachename), 600); if (empty($otherInfo)) { $otherInfo = array(); $otherInfo['category'] = xss_esc_back($row['category']); $otherInfo['groups'] = UserGroups::getVideoGroups($row['id']); $otherInfo['tags'] = self::getTags($row['id']); $otherInfo['title'] = UTF8encode($row['title']); $otherInfo['description'] = UTF8encode($row['description']); $otherInfo['descriptionHTML'] = self::htmlDescription($otherInfo['description']); if (empty($row['filesize'])) { $otherInfo['filesize'] = Video::updateFilesize($row['id']); } ObjectYPT::setCache($otherInfocachename, $otherInfo); } foreach ($otherInfo as $key => $value) { $row[$key] = $value; } $row['progress'] = self::getVideoPogressPercent($row['id']); $row['isFavorite'] = self::isFavorite($row['id']); $row['isWatchLater'] = self::isWatchLater($row['id']); $row['favoriteId'] = self::getFavoriteIdFromUser(User::getId()); $row['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId()); TimeLogEnd("video::getAllVideos otherInfo", __LINE__, 0.5); TimeLogStart("video::getAllVideos getAllVideosArray"); $row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id'])); TimeLogEnd("video::getAllVideos getAllVideosArray", __LINE__); $videos[] = $row; } $rowCount = getRowCount(); - $tolerance = $rowCount/100; - if($tolerance<0.2){ - $tolerance=0.2; - }else if($tolerance>2){ - $tolerance=2; + $tolerance = $rowCount / 100; + if ($tolerance < 0.2) { + $tolerance = 0.2; + } else if ($tolerance > 2) { + $tolerance = 2; } TimeLogEnd("video::getAllVideos foreach", __LINE__, $tolerance); //$videos = $res->fetch_all(MYSQLI_ASSOC); } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $videos; } public static function htmlDescription($description) { if (strip_tags($description) != $description) { return $description; } else { return nl2br(textToLink(htmlentities($description))); } } public static function isFavorite($videos_id) { if (AVideoPlugin::isEnabledByName("PlayLists")) { return PlayList::isVideoOnFavorite($videos_id, User::getId()); } return false; } public static function isSerie($videos_id) { $v = new Video("", "", $videos_id); return !empty($v->getSerie_playlists_id()); } public static function isWatchLater($videos_id) { if (AVideoPlugin::isEnabledByName("PlayLists")) { return PlayList::isVideoOnWatchLater($videos_id, User::getId()); } return false; } public static function getFavoriteIdFromUser($users_id) { if (AVideoPlugin::isEnabledByName("PlayLists")) { return PlayList::getFavoriteIdFromUser($users_id); } return false; } public static function getWatchLaterIdFromUser($users_id) { if (AVideoPlugin::isEnabledByName("PlayLists")) { return PlayList::getWatchLaterIdFromUser($users_id); } return false; } public static function updateFilesize($videos_id) { global $config; if ($config->currentVersionLowerThen('8.5')) { return false; } TimeLogStart("Video::updateFilesize {$videos_id}"); ini_set('max_execution_time', 300); // 5 set_time_limit(300); $video = new Video("", "", $videos_id); $filename = $video->getFilename(); if (empty($filename) || !($video->getType() == "video" || $video->getType() == "audio" || $video->getType() == "zip" || $video->getType() == "image")) { //_error_log("updateFilesize: Not updated, this filetype is ".$video->getType()); return false; } $filesize = getUsageFromFilename($filename); if (empty($filesize)) { $obj = AVideoPlugin::getObjectDataIfEnabled("DiskUploadQuota"); if (!empty($obj->deleteVideosWith0Bytes)) { try { _error_log("updateFilesize: DELETE videos_id=$videos_id filename=$filename filesize=$filesize"); return $video->delete(); } catch (Exception $exc) { _error_log("updateFilesize: ERROR " . $exc->getTraceAsString()); return false; } } } if ($video->getFilesize() == $filesize) { //_error_log("updateFilesize: No need to update videos_id=$videos_id filename=$filename filesize=$filesize"); return $filesize; } $video->setFilesize($filesize); TimeLogEnd("Video::updateFilesize {$videos_id}", __LINE__); if ($video->save(false, true)) { _error_log("updateFilesize: videos_id=$videos_id filename=$filename filesize=$filesize"); return $filesize; } else { _error_log("updateFilesize: ERROR videos_id=$videos_id filename=$filename filesize=$filesize"); return false; } } public static function getAllVideosAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true) { global $global, $advancedCustom; $return = array(); $users_id = User::getId(); $get = json_encode(@$_GET); $post = json_encode(@$_POST); $md5 = md5("{$users_id}{$get}{$post}{$status}{$showOnlyLoggedUserVideos}{$ignoreGroup}" . implode("_", $videosArrayId) . "{$getStatistcs}{$showUnlisted}{$activeUsersOnly}"); $path = getCacheDir() . "getAllVideosAsync/"; make_path($path); $cacheFileName = "{$path}{$md5}"; if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName) || filesize($cacheFileName) === 0) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = _json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getAllVideosAsync.php' '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup' '" . json_encode($videosArrayId) . "' '$getStatistcs' '$showUnlisted' '$activeUsersOnly' '{$get}' '{$post}' '{$cacheFileName}'"); _error_log("getAllVideosAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return object_to_array($return); } /** * Same as getAllVideos() method but a lighter query * @global type $global * @global type $config * @param type $showOnlyLoggedUserVideos * @return boolean */ public static function getAllVideosLight($status = "viewable", $showOnlyLoggedUserVideos = false, $showUnlisted = false, $suggestedOnly = false) { global $global, $config; if ($config->currentVersionLowerThen('5')) { return false; } $status = str_replace("'", "", $status); $sql = "SELECT v.* " . " FROM videos as v " . " WHERE 1=1 "; $blockedUsers = self::getBlockedUsersIdsArray(); if (!empty($blockedUsers)) { $sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') "; } if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $sql .= " AND v.users_id = '{$user['id']}' "; } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; $sql .= " ORDER BY RAND() "; } if (strpos(strtolower($sql), 'limit') === false) { if (empty($global['limitForUnlimitedVideos'])) { $global['limitForUnlimitedVideos'] = empty($global['rowCount']) ? 1000 : $global['rowCount']; } if ($global['limitForUnlimitedVideos'] > 0) { $sql .= " LIMIT {$global['limitForUnlimitedVideos']}"; } } //echo $sql; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); // if there is a search, and there is no data and is inside a channel try again without a channel if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) { $channelName = $_GET['channelName']; unset($_GET['channelName']); $return = self::getAllVideosLight($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly); $_GET['channelName'] = $channelName; return $return; } sqlDAL::close($res); $videos = array(); if ($res != false) { foreach ($fullData as $row) { if (empty($row['filesize'])) { $row['filesize'] = Video::updateFilesize($row['id']); } $videos[] = $row; } //$videos = $res->fetch_all(MYSQLI_ASSOC); } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $videos; } public static function getTotalVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false) { global $global, $config, $advancedCustomUser; if ($config->currentVersionLowerThen('5')) { return false; } if (!empty($_POST['sort']['suggested'])) { $suggestedOnly = true; } $status = str_replace("'", "", $status); $cn = ""; if (!empty($_GET['catName'])) { $cn .= ", c.clean_name as cn"; } if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})"); $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__); } } $sql = "SELECT v.users_id, v.type, v.id, v.title,v.description, c.name as category {$cn} " . "FROM videos v " . "LEFT JOIN categories c ON categories_id = c.id " . " LEFT JOIN users u ON v.users_id = u.id " . " WHERE 1=1 "; $blockedUsers = self::getBlockedUsersIdsArray(); if (!empty($blockedUsers)) { $sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') "; } if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL('v.'); } if (!empty($videosArrayId) && is_array($videosArrayId)) { $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; } if ($status == "viewable") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (is_int($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if (isset($_REQUEST['is_serie'])) { $is_serie = intval($_REQUEST['is_serie']); if (empty($is_serie)) { $sql .= " AND v.serie_playlists_id IS NULL "; } else { $sql .= " AND v.serie_playlists_id IS NOT NULL "; } } if (!empty($_GET['catName'])) { $catName = $global['mysqli']->real_escape_string($_GET['catName']); $sql .= " AND c.clean_name = '{$catName}'"; } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } elseif ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if (!$ignoreGroup) { $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } } if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $uid = intval($user['id']); $sql .= " AND v.users_id = '{$uid}' "; } $sql .= AVideoPlugin::getVideoWhereClause(); if (!empty($_POST['searchPhrase'])) { $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description'); - if($advancedCustomUser->videosSearchAlsoSearchesOnChannelName){ + if ($advancedCustomUser->videosSearchAlsoSearchesOnChannelName) { $searchFieldsNames[] = 'u.channelName'; } if (AVideoPlugin::isEnabledByName("VideoTags")) { $sql .= " AND ("; $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; $sql .= BootGrid::getSqlSearchFromPost($searchFieldsNames, "OR"); $searchFieldsNames = array('v.title'); $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']); $sql .= ")"; } else { $sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames); $searchFieldsNames = array('v.title'); $sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']) . ')'; } } if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; } $res = sqlDAL::readSql($sql); $numRows = sqlDal::num_rows($res); sqlDAL::close($res); // if there is a search, and there is no data and is inside a channel try again without a channel if (!empty($_GET['search']) && empty($numRows) && !empty($_GET['channelName'])) { $channelName = $_GET['channelName']; unset($_GET['channelName']); $return = self::getTotalVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly); $_GET['channelName'] = $channelName; return $return; } return $numRows; } public static function getTotalVideosInfo($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array()) { $obj = new stdClass(); $obj->likes = 0; $obj->disLikes = 0; $obj->views_count = 0; $obj->total_minutes = 0; $videos = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId); foreach ($videos as $value) { $obj->likes += intval($value['likes']); $obj->disLikes += intval($value['dislikes']); $obj->views_count += intval($value['views_count']); $obj->total_minutes += intval(parseDurationToSeconds($value['duration']) / 60); } return $obj; } public static function getTotalVideosInfoAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false) { global $global, $advancedCustom; $path = getCacheDir() . "getTotalVideosInfo/"; make_path($path); $cacheFileName = "{$path}_{$status}_{$showOnlyLoggedUserVideos}_{$ignoreGroup}_" . implode($videosArrayId) . "_{$getStatistcs}"; $return = array(); if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getTotalVideosInfo($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = _json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalVideosInfoAsync.php' " . " '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup', '" . json_encode($videosArrayId) . "', " . " '$getStatistcs', '$cacheFileName'"); //_error_log("getTotalVideosInfoAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } public static function getViewableStatus($showUnlisted = false) { /** a = active k = active and encoding i = inactive e = encoding x = encoding error d = downloading u = unlisted - xmp4 = encoding mp4 error - xwebm = encoding webm error - xmp3 = encoding mp3 error - xogg = encoding ogg error */ - $viewable = array('a', 'k', 'xmp4', 'xwebm', 'xmp3', 'xogg'); + $viewable = array('a', 'k'); if ($showUnlisted) { $viewable[] = "u"; } elseif (!empty($_GET['videoName'])) { $post = $_POST; if (self::isOwnerFromCleanTitle($_GET['videoName']) || Permissions::canModerateVideos()) { $viewable[] = "u"; } $_POST = $post; } return $viewable; } public static function getVideoConversionStatus($filename) { global $global; require_once $global['systemRootPath'] . 'objects/user.php'; if (!User::isLogged()) { die("Only logged users can upload"); } $object = new stdClass(); foreach (self::$types as $value) { $progressFilename = self::getStoragePathFromFileName($filename) . "progress_{$value}.txt"; $content = @url_get_contents($progressFilename); $object->$value = new stdClass(); if (!empty($content)) { $object->$value = self::parseProgress($content); } else { } if (!empty($object->$value->progress) && !is_numeric($object->$value->progress)) { $video = self::getVideoFromFileName($filename); //var_dump($video, $filename); if (!empty($video)) { $object->$value->progress = self::$statusDesc[$video['status']]; } } $object->$value->filename = $progressFilename; } return $object; } private static function parseProgress($content) { //get duration of source $obj = new stdClass(); $obj->duration = 0; $obj->currentTime = 0; $obj->progress = 0; //var_dump($content);exit; preg_match("/Duration: (.*?), start:/", $content, $matches); if (!empty($matches[1])) { $rawDuration = $matches[1]; //rawDuration is in 00:00:00.00 format. This converts it to seconds. $ar = array_reverse(explode(":", $rawDuration)); $duration = floatval($ar[0]); if (!empty($ar[1])) { $duration += intval($ar[1]) * 60; } if (!empty($ar[2])) { $duration += intval($ar[2]) * 60 * 60; } //get the time in the file that is already encoded preg_match_all("/time=(.*?) bitrate/", $content, $matches); $rawTime = array_pop($matches); //this is needed if there is more than one match if (is_array($rawTime)) { $rawTime = array_pop($rawTime); } //rawTime is in 00:00:00.00 format. This converts it to seconds. $ar = array_reverse(explode(":", $rawTime)); $time = floatval($ar[0]); if (!empty($ar[1])) { $time += intval($ar[1]) * 60; } if (!empty($ar[2])) { $time += intval($ar[2]) * 60 * 60; } if (!empty($duration)) { //calculate the progress $progress = round(($time / $duration) * 100); } else { $progress = 'undefined'; } $obj->duration = $duration; $obj->currentTime = $time; $obj->progress = $progress; } return $obj; } public function delete($allowOfflineUser = false) { if (!$allowOfflineUser && !$this->userCanManageVideo()) { return false; } global $global; if (!empty($this->id)) { $this->removeNextVideos($this->id); $this->removeTrailerReference($this->id); $this->removeCampaign($this->id); $video = self::getVideoLight($this->id); $sql = "DELETE FROM videos WHERE id = ?"; } else { return false; } $resp = sqlDAL::writeSql($sql, "i", array($this->id)); if ($resp == false) { _error_log('Error (delete on video) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); return false; } else { $this->removeVideoFiles(); } return $resp; } public function removeVideoFiles() { $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); $YPTStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage'); if (!empty($aws_s3)) { $aws_s3->removeFiles($this->getFilename()); } if (!empty($bb_b2)) { $bb_b2->removeFiles($this->getFilename()); } if (!empty($ftp)) { $ftp->removeFiles($this->getFilename()); } if (!empty($YPTStorage) && !empty($this->getSites_id())) { $YPTStorage->removeFiles($this->getFilename(), $this->getSites_id()); } $this->removeFiles($this->getFilename()); self::deleteThumbs($this->getFilename()); } private function removeNextVideos($videos_id) { if (!$this->userCanManageVideo()) { return false; } global $global; if (!empty($videos_id)) { $sql = "UPDATE videos SET next_videos_id = NULL WHERE next_videos_id = ?"; sqlDAL::writeSql($sql, "s", array($videos_id)); } else { return false; } return true; } private function removeTrailerReference($videos_id) { if (!$this->userCanManageVideo()) { return false; } global $global; if (!empty($videos_id)) { $videoURL = self::getLink($videos_id, '', true); $sql = "UPDATE videos SET trailer1 = '' WHERE trailer1 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); $sql = "UPDATE videos SET trailer2 = '' WHERE trailer2 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); $sql = "UPDATE videos SET trailer3 = '' WHERE trailer3 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); } else { return false; } return true; } private function removeCampaign($videos_id) { if (ObjectYPT::isTableInstalled('vast_campaigns_has_videos')) { if (!empty($this->id)) { $sql = "DELETE FROM vast_campaigns_has_videos "; $sql .= " WHERE videos_id = ?"; $global['lastQuery'] = $sql; return sqlDAL::writeSql($sql, "i", array($videos_id)); } } return false; } private function removeFiles($filename) { if (empty($filename)) { return false; } global $global; $file = self::getStoragePath() . "original_{$filename}"; $this->removeFilePath($file); $files = self::getStoragePath() . "{$filename}"; $this->removeFilePath($files); } private function removeFilePath($filePath) { if (empty($filePath)) { return false; } // Streamlined for less coding space. $files = glob("{$filePath}*"); foreach ($files as $file) { if (file_exists($file)) { if (is_dir($file)) { self::rrmdir($file); } else { @unlink($file); } } } } private static function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir . "/" . $object)) { self::rrmdir($dir . "/" . $object); } else { unlink($dir . "/" . $object); } } } rmdir($dir); } } public function setDescription($description) { global $global, $advancedCustom; if (empty($advancedCustom->disableHTMLDescription)) { $articleObj = AVideoPlugin::getObjectData('Articles'); $configPuri = HTMLPurifier_Config::createDefault(); $purifier = new HTMLPurifier($configPuri); if (empty($articleObj->allowAttributes)) { $configPuri->set('HTML.AllowedAttributes', array('a.href', 'a.target', 'a.title', 'a.title', 'img.src', 'img.width', 'img.height')); // remove all attributes except a.href $configPuri->set('Attr.AllowedFrameTargets', array('_blank')); } if (empty($articleObj->allowAttributes)) { $configPuri->set('CSS.AllowedProperties', array()); // remove all CSS } $configPuri->set('AutoFormat.RemoveEmpty', true); // remove empty elements $pure = $purifier->purify($description); $parts = explode("", $pure); if (!empty($parts[1])) { $parts = explode("", $parts[1]); } $new_description = $parts[0]; } else { $new_description = strip_tags(br2nl($description)); } AVideoPlugin::onVideoSetDescription($this->id, $this->description, $new_description); $this->description = $new_description; //var_dump($this->description, $description, $parts);exit; } public function setCategories_id($categories_id) { if (!Category::userCanAddInCategory($categories_id)) { return false; } // to update old cat as well when auto.. if (!empty($this->categories_id)) { $this->old_categories_id = $this->categories_id; } AVideoPlugin::onVideoSetCategories_id($this->id, $this->categories_id, $categories_id); $this->categories_id = $categories_id; } public static function getCleanDuration($duration = "") { if (empty($duration)) { if (!empty($this) && !empty($this->duration)) { $durationParts = explode(".", $this->duration); } else { return "00:00:00"; } } else { $durationParts = explode(".", $duration); } if (empty($durationParts[0])) { return "00:00:00"; } else { $duration = $durationParts[0]; $durationParts = explode(':', $duration); if (count($durationParts) == 1) { return '0:00:' . static::addZero($durationParts[0]); } elseif (count($durationParts) == 2) { return '0:' . static::addZero($durationParts[0]) . ':' . static::addZero($durationParts[1]); } return $duration; } } private static function addZero($str) { if (intval($str) < 10) { return '0' . intval($str); } return $str; } public static function getItemPropDuration($duration = '') { $duration = static::getCleanDuration($duration); $parts = explode(':', $duration); $duration = 'PT' . intval($parts[0]) . 'H' . intval($parts[1]) . 'M' . intval($parts[2]) . 'S'; if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } return $duration; } public static function getItemDurationSeconds($duration = '') { if ($duration == "EE:EE:EE") { return 0; } $duration = static::getCleanDuration($duration); $parts = explode(':', $duration); return intval($parts[0] * 60 * 60) + intval($parts[1] * 60) + intval($parts[2]); } public static function getDurationFromFile($file) { global $global; // get movie duration HOURS:MM:SS.MICROSECONDS if (!file_exists($file)) { _error_log('{"status":"error", "msg":"getDurationFromFile ERROR, File (' . $file . ') Not Found"}'); return "EE:EE:EE"; } // Initialize getID3 engine $getID3 = new getID3; // Analyze file and store returned data in $ThisFileInfo $ThisFileInfo = $getID3->analyze($file); return static::getCleanDuration(@$ThisFileInfo['playtime_string']); } public static function getResolution($file) { global $videogetResolution; if (!isset($videogetResolution)) { $videogetResolution = array(); } if (isset($videogetResolution[$file])) { return $videogetResolution[$file]; } if ( AVideoPlugin::isEnabledByName("Blackblaze_B2") || AVideoPlugin::isEnabledByName("AWS_S3") || AVideoPlugin::isEnabledByName("FTP_Storage") || AVideoPlugin::isEnabledByName("YPTStorage") || !file_exists($file)) { $videogetResolution[$file] = 0; return 0; } global $global; if (preg_match("/.m3u8$/i", $file) && AVideoPlugin::isEnabledByName('VideoHLS') && method_exists(new VideoHLS(), 'getHLSHigestResolutionFromFile')) { $videogetResolution[$file] = VideoHLS::getHLSHigestResolutionFromFile($file); } else { $getID3 = new getID3; $ThisFileInfo = $getID3->analyze($file); $videogetResolution[$file] = intval(@$ThisFileInfo['video']['resolution_y']); } return $videogetResolution[$file]; } public static function getHLSDurationFromFile($file) { $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (empty($plugin)) { return 0; } return VideoHLS::getHLSDurationFromFile($file); } public function updateHLSDurationIfNeed() { $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (empty($plugin)) { return false; } return VideoHLS::updateHLSDurationIfNeed($this); } public function updateDurationIfNeed($fileExtension = ".mp4") { global $global; $source = self::getSourceFile($this->filename, $fileExtension, true); $file = $source['path']; if (!empty($this->id) && $this->duration == "EE:EE:EE" && file_exists($file)) { $this->duration = Video::getDurationFromFile($file); _error_log("Duration Updated: " . json_encode($this)); $sql = "UPDATE videos SET duration = ?, modified = now() WHERE id = ?"; $res = sqlDAL::writeSql($sql, "si", array($this->duration, $this->id)); return $this->id; } else { _error_log("Do not need update duration: "); return false; } } public function getFilename() { return $this->filename; } public function getStatus() { return $this->status; } public function getId() { return $this->id; } public function getVideoDownloadedLink() { return $this->videoDownloadedLink; } public function setVideoDownloadedLink($videoDownloadedLink) { AVideoPlugin::onVideoSetVideoDownloadedLink($this->id, $this->videoDownloadedLink, $videoDownloadedLink); $this->videoDownloadedLink = $videoDownloadedLink; } public static function isLandscape($pathFileName) { global $config; // get movie duration HOURS:MM:SS.MICROSECONDS if (!file_exists($pathFileName)) { echo '{"status":"error", "msg":"isLandscape ERROR, File (' . $pathFileName . ') Not Found"}'; return true; } eval('$cmd="' . $config->getExiftool() . '";'); $resp = true; // is landscape by default exec($cmd . ' 2>&1', $output, $return_val); if ($return_val !== 0) { $resp = true; } else { $w = 1; $h = 0; $rotation = 0; foreach ($output as $value) { preg_match("/Image Size.*:[^0-9]*([0-9]+x[0-9]+)/i", $value, $match); if (!empty($match)) { $parts = explode("x", $match[1]); $w = $parts[0]; $h = $parts[1]; } preg_match("/Rotation.*:[^0-9]*([0-9]+)/i", $value, $match); if (!empty($match)) { $rotation = $match[1]; } } if ($rotation == 0) { if ($w > $h) { $resp = true; } else { $resp = false; } } else { if ($w < $h) { $resp = true; } else { $resp = false; } } } //var_dump($cmd, $w, $h, $rotation, $resp);exit; return $resp; } public function userCanManageVideo() { global $advancedCustomUser; if (Permissions::canAdminVideos()) { return true; } if (empty($this->users_id) || !User::canUpload()) { return false; } // if you not admin you can only manager yours video $users_id = $this->users_id; if ($advancedCustomUser->userCanChangeVideoOwner) { $video = new Video("", "", $this->id); // query again to make sure the user is not changing the owner $users_id = $video->getUsers_id(); } if ($users_id != User::getId()) { return false; } return true; } public function getVideoGroups() { return $this->videoGroups; } public function setVideoGroups($userGroups) { if (is_array($userGroups)) { AVideoPlugin::onVideoSetVideoGroups($this->id, $this->videoGroups, $userGroups); $this->videoGroups = $userGroups; } } /** * * @param type $user_id * text * label Default Primary Success Info Warning Danger */ public static function getTags($video_id, $type = "") { global $advancedCustom, $videos_getTags; if (empty($videos_getTags)) { $videos_getTags = array(); } $name = "{$video_id}_{$type}"; if (!empty($videos_getTags[$name])) { return $videos_getTags[$name]; } if (empty($advancedCustom->AsyncJobs)) { $videos_getTags[$name] = self::getTags_($video_id, $type); return $videos_getTags[$name]; } else { $tags = self::getTagsAsync($video_id, $type); foreach ($tags as $key => $value) { if (is_array($value)) { $tags[$key] = (object) $value; } } $videos_getTags[$name] = $tags; return $tags; } } public static function getTagsHTMLLabelArray($video_id) { global $_getTagsHTMLLabelArray; if (!isset($_getTagsHTMLLabelArray)) { $_getTagsHTMLLabelArray = array(); } if (isset($_getTagsHTMLLabelArray[$video_id])) { return $_getTagsHTMLLabelArray[$video_id]; } $tags = Video::getTags($video_id); $_getTagsHTMLLabelArray[$video_id] = array(); foreach ($tags as $value2) { if (empty($value2->label) || ($value2->label !== __("Paid Content") && $value2->label !== __("Group") && $value2->label !== __("Plugin"))) { continue; } $tooltip = ''; if (!empty($value2->tooltip)) { $icon = $value2->text; if (!empty($value2->tooltipIcon)) { $icon = $value2->tooltipIcon; } $tooltip = ' data-toggle="tooltip" title="' . htmlentities($icon . ' ' . $value2->tooltip) . '" data-html="true"'; } $_getTagsHTMLLabelArray[$video_id][] = '' . $value2->text . ''; } return $_getTagsHTMLLabelArray[$video_id]; } public static function getTags_($video_id, $type = "") { global $advancedCustom, $advancedCustomUser; if (empty($advancedCustom)) { $advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser"); } if (empty($advancedCustom)) { $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); } $currentPage = getCurrentPage(); $rowCount = getRowCount(); $_REQUEST['current'] = 1; $_REQUEST['rowCount'] = 1000; $video = new Video("", "", $video_id); $tags = array(); if (empty($type) || $type === "paid") { $objTag = new stdClass(); $objTag->label = __("Paid Content"); if (!empty($advancedCustom->paidOnlyShowLabels)) { if (!empty($video->getOnly_for_paid())) { $objTag->type = "warning"; $objTag->text = ''; $objTag->tooltip = $advancedCustom->paidOnlyLabel; } else { $objTag->type = "success"; $objTag->text = ''; $objTag->tooltip = $advancedCustom->paidOnlyFreeLabel; } } else { $ppv = AVideoPlugin::getObjectDataIfEnabled("PayPerView"); if ($advancedCustomUser->userCanProtectVideosWithPassword && !empty($video->getVideo_password())) { $objTag->type = "danger"; $objTag->text = ''; $objTag->tooltip = __("Password Protected"); } elseif (!empty($video->getOnly_for_paid())) { $objTag->type = "warning"; $objTag->text = ''; $objTag->tooltip = $advancedCustom->paidOnlyLabel; } elseif ($ppv && PayPerView::isVideoPayPerView($video_id)) { if (!empty($ppv->showPPVLabel)) { $objTag->type = "warning"; $objTag->text = "PPV"; $objTag->tooltip = __("Pay Per View"); } else { $objTag->type = "warning"; $objTag->text = ''; $objTag->tooltip = __("Private"); } } elseif (!Video::isPublic($video_id)) { $objTag->type = "warning"; $objTag->text = ''; $objTag->tooltip = __("Private"); } else { $objTag->type = "success"; $objTag->text = ''; $objTag->tooltip = $advancedCustom->paidOnlyFreeLabel; } } $tags[] = $objTag; $objTag = new stdClass(); } /** a = active i = inactive e = encoding x = encoding error d = downloading u = unlisted - xmp4 = encoding mp4 error - xwebm = encoding webm error - xmp3 = encoding mp3 error - xogg = encoding ogg error - ximg = get image error */ if (empty($type) || $type === "status") { $objTag = new stdClass(); $objTag->label = __("Status"); - switch ($video->getStatus()) { - case 'a': + $status = $video->getStatus(); + $objTag->text = __(Video::$statusDesc[$status]); + switch ($status) { + case Video::$statusActive: $objTag->type = "success"; - $objTag->text = __("Active"); break; - case 'k': + case Video::$statusActiveAndEncoding: $objTag->type = "success"; - $objTag->text = __("Active and encoding"); break; - case 'i': + case Video::$statusInactive: $objTag->type = "warning"; - $objTag->text = __("Inactive"); break; - case 'e': + case Video::$statusEncoding: $objTag->type = "info"; - $objTag->text = __("Encoding"); break; - case 'd': + case Video::$statusDownloading: $objTag->type = "info"; - $objTag->text = __("Downloading"); break; - case 'u': + case Video::$statusUnlisted: $objTag->type = "info"; - $objTag->text = __("Unlisted"); break; - case 'xmp4': - $objTag->type = "danger"; - $objTag->text = __("Encoding mp4 error"); - break; - case 'xwebm': - $objTag->type = "danger"; - $objTag->text = __("Encoding xwebm error"); - break; - case 'xmp3': - $objTag->type = "danger"; - $objTag->text = __("Encoding xmp3 error"); - break; - case 'xogg': - $objTag->type = "danger"; - $objTag->text = __("Encoding xogg error"); - break; - case 'ximg': - $objTag->type = "danger"; - $objTag->text = __("Get imgage error"); - break; - default: $objTag->type = "danger"; - $objTag->text = __("Status not found"); break; } $objTag->text = $objTag->text; $tags[] = $objTag; $objTag = new stdClass(); } if (empty($type) || $type === "userGroups") { $groups = UserGroups::getVideoGroups($video_id); $objTag = new stdClass(); $objTag->label = __("Group"); if (empty($groups)) { $status = $video->getStatus(); if ($status == 'u') { $objTag->type = "info"; $objTag->text = ''; $objTag->tooltip = __("Unlisted"); $tags[] = $objTag; $objTag = new stdClass(); } else { //$objTag->type = "success"; //$objTag->text = __("Public"); } } else { foreach ($groups as $value) { $objTag = new stdClass(); $objTag->label = __("Group"); $objTag->type = "info"; $objTag->text = ''; $objTag->tooltip = $value['group_name']; $tags[] = $objTag; $objTag = new stdClass(); } } } if (empty($type) || $type === "category") { require_once 'category.php'; $sort = null; if (!empty($_POST['sort']['title'])) { $sort = $_POST['sort']; unset($_POST['sort']); } $category = Category::getCategory($video->getCategories_id()); if (!empty($sort)) { $_POST['sort'] = $sort; } $objTag = new stdClass(); $objTag->label = __("Category"); if (!empty($category)) { $objTag->type = "default"; $objTag->text = $category['name']; $tags[] = $objTag; $objTag = new stdClass(); } } if (empty($type) || $type === "source") { $url = $video->getVideoDownloadedLink(); $parse = parse_url($url); $objTag = new stdClass(); $objTag->label = __("Source"); if (!empty($parse['host'])) { $objTag->type = "danger"; $objTag->text = $parse['host']; $tags[] = $objTag; $objTag = new stdClass(); } else { $objTag->type = "info"; $objTag->text = __("Local File"); $tags[] = $objTag; $objTag = new stdClass(); } } $array2 = AVideoPlugin::getVideoTags($video_id); if (is_array($array2)) { $tags = array_merge($tags, $array2); } //var_dump($tags); $_REQUEST['current'] = $currentPage; $_REQUEST['rowCount'] = $rowCount; return $tags; } public static function deleteTagsAsync($video_id) { global $global; if (empty($video_id)) { return false; } $name = "getVideoTags{$video_id}"; ObjectYPT::deleteCache($name); _session_start(); unset($_SESSION['getVideoTags'][$video_id]); $path = getCacheDir() . "getTagsAsync/"; if (!is_dir($path)) { return false; } $cacheFileName = "{$path}_{$video_id}_"; $files = glob("{$cacheFileName}*"); foreach ($files as $file) { unlink($file); } } public static function getTagsAsync($video_id, $type = "video") { global $global, $advancedCustom; $path = getCacheDir() . "getTagsAsync/"; make_path($path); $cacheFileName = "{$path}_{$video_id}_{$type}"; $return = array(); if (!file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getTags_($video_id, $type); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = _json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 300) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTags.php' '$video_id' '$type' '{$cacheFileName}'"); //_error_log("getTags: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return (array) $return; } public function getCategories_id() { return $this->categories_id; } public function getType() { return $this->type; } public static function fixCleanTitle($clean_title, $count, $videoId, $original_title = "") { global $global; if (empty($original_title)) { $original_title = $clean_title; } $sql = "SELECT * FROM videos WHERE clean_title = '{$clean_title}' "; if (!empty($videoId)) { $sql .= " AND id != {$videoId} "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $cleanTitleExists = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($cleanTitleExists != false) { return self::fixCleanTitle($original_title . "-" . $count, $count + 1, $videoId, $original_title); } return $clean_title; } /** * * @global type $global * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ public static function isOwner($videos_id, $users_id = 0) { global $global; if (empty($users_id)) { $users_id = User::getId(); if (empty($users_id)) { return false; } } $video_owner = self::getOwner($videos_id); if ($video_owner) { if ($video_owner == $users_id) { return true; } } return false; } public static function isOwnerFromCleanTitle($clean_title, $users_id = 0) { global $global; $video = self::getVideoFromCleanTitle($clean_title); return self::isOwner($video['id'], $users_id); } /** * * @global type $global * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ public static function getOwner($videos_id) { global $global; $sql = "SELECT users_id FROM videos WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { if ($videoRow != false) { return $videoRow['users_id']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } /** * * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ public static function canEdit($videos_id, $users_id = 0) { if (empty($videos_id)) { return false; } if (empty($users_id)) { $users_id = User::getId(); if (empty($users_id)) { return false; } } $user = new User($users_id); if (empty($user)) { return false; } if ($user->getIsAdmin()) { return true; } if (Permissions::canAdminVideos()) { return true; } return self::isOwner($videos_id, $users_id); } public static function getRandom($excludeVideoId = false) { return static::getVideo("", "viewable", false, $excludeVideoId); } public static function getVideoQueryFileter() { global $global; $sql = ""; if (!empty($_GET['playlist_id'])) { require_once $global['systemRootPath'] . 'objects/playlist.php'; $ids = PlayList::getVideosIdFromPlaylist($_GET['playlist_id']); if (!empty($ids)) { $sql .= " AND v.id IN (" . implode(",", $ids) . ") "; } } return $sql; } public function getTitle() { return $this->title; } public function getClean_title() { return $this->clean_title; } public function getDescription() { return $this->description; } public function getExistingVideoFile() { $source = self::getHigestResolutionVideoMP4Source($this->getFilename(), true); if (empty($source)) { _error_log("getExistingVideoFile:: resources are empty " . $this->getFilename()); return false; } $size = filesize($source['path']); if ($size <= 20) {// it is a dummy file $url = $source['url']; _error_log("getExistingVideoFile:: dummy file, download it " . json_encode($source)); $filename = getTmpDir("getExistingVideoFile") . md5($url); copyfile_chunked($url, $filename); wget($url, $filename); return $filename; } return $source['path']; } public function getTrailer1() { return $this->trailer1; } public function getTrailer2() { return $this->trailer2; } public function getTrailer3() { return $this->trailer3; } public function getRate() { return $this->rate; } public function setTrailer1($trailer1) { if (filter_var($trailer1, FILTER_VALIDATE_URL)) { $new_trailer1 = $trailer1; } else { $new_trailer1 = ""; } AVideoPlugin::onVideoSetTrailer1($this->id, $this->trailer1, $new_trailer1); $this->trailer1 = $new_trailer1; } public function setTrailer2($trailer2) { if (filter_var($trailer2, FILTER_VALIDATE_URL)) { $new_trailer2 = $trailer2; } else { $new_trailer2 = ""; } AVideoPlugin::onVideoSetTrailer2($this->id, $this->trailer2, $new_trailer2); $this->trailer2 = $new_trailer2; } public function setTrailer3($trailer3) { if (filter_var($trailer3, FILTER_VALIDATE_URL)) { $new_trailer3 = $trailer3; } else { $new_trailer3 = ""; } AVideoPlugin::onVideoSetTrailer3($this->id, $this->trailer3, $new_trailer3); $this->trailer3 = $new_trailer3; } public function setRate($rate) { AVideoPlugin::onVideoSetRate($this->id, $this->rate, floatval($rate)); $this->rate = floatval($rate); } public function getYoutubeId() { return $this->youtubeId; } public function setYoutubeId($youtubeId) { AVideoPlugin::onVideoSetYoutubeId($this->id, $this->youtubeId, $youtubeId); $this->youtubeId = $youtubeId; } public function setTitle($title) { if ($title === "Video automatically booked" && !empty($this->title)) { return false; } $new_title = strip_tags($title); if (strlen($new_title) > 190) { $new_title = substr($new_title, 0, 187) . '...'; } AVideoPlugin::onVideoSetTitle($this->id, $this->title, $new_title); $this->title = $new_title; } public function setFilename($filename, $force = false) { if ($force || empty($this->filename)) { AVideoPlugin::onVideoSetFilename($this->id, $this->filename, $filename, $force); $this->filename = $filename; - }else{ - _error_log('setFilename: fail '.$filename." {$this->id}"); + } else { + _error_log('setFilename: fail ' . $filename . " {$this->id}"); } return $this->filename; } public function getNext_videos_id() { return $this->next_videos_id; } public function setNext_videos_id($next_videos_id) { AVideoPlugin::onVideoSetNext_videos_id($this->id, $this->next_videos_id, $next_videos_id); $this->next_videos_id = $next_videos_id; } public function queue($types = array()) { global $config; if (!User::canUpload()) { return false; } global $global; $obj = new stdClass(); $obj->error = true; $target = $config->getEncoderURL() . "queue"; $postFields = array( 'user' => User::getUserName(), 'pass' => User::getUserPass(), 'fileURI' => $global['webSiteRootURL'] . "videos/original_{$this->getFilename()}", 'filename' => $this->getFilename(), 'videos_id' => $this->getId(), "notifyURL" => "{$global['webSiteRootURL']}" ); if (empty($types) && AVideoPlugin::isEnabledByName("VideoHLS")) { $postFields['inputHLS'] = 1; } elseif (!empty($types)) { foreach ($types as $key => $value) { $postFields[$key] = $value; } } _error_log("SEND To QUEUE: ($target) " . json_encode($postFields)); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $target); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); $r = curl_exec($curl); $obj->response = $r; if ($errno = curl_errno($curl)) { $error_message = curl_strerror($errno); //echo "cURL error ({$errno}):\n {$error_message}"; $obj->msg = "cURL error ({$errno}):\n {$error_message}"; } else { $obj->error = false; } _error_log("QUEUE CURL: ($target) " . json_encode($obj)); curl_close($curl); return $obj; } public function getVideoLink() { return $this->videoLink; } public function setVideoLink($videoLink) { AVideoPlugin::onVideoSetVideoLink($this->id, $this->videoLink, $videoLink); $this->videoLink = $videoLink; } public function getCan_download() { return $this->can_download; } public function getCan_share() { return $this->can_share; } public function setCan_download($can_download) { $new_can_download = (empty($can_download) || $can_download === "false") ? 0 : 1; AVideoPlugin::onVideoSetCan_download($this->id, $this->can_download, $new_can_download); $this->can_download = $new_can_download; } public function setCan_share($can_share) { $new_can_share = (empty($can_share) || $can_share === "false") ? 0 : 1; AVideoPlugin::onVideoSetCan_share($this->id, $this->can_share, $new_can_share); $this->can_share = $new_can_share; } public function getOnly_for_paid() { return $this->only_for_paid; } public function setOnly_for_paid($only_for_paid) { $new_only_for_paid = (empty($only_for_paid) || $only_for_paid === "false") ? 0 : 1; AVideoPlugin::onVideoSetOnly_for_paid($this->id, $this->only_for_paid, $new_only_for_paid); $this->only_for_paid = $new_only_for_paid; } /** * * @param type $filename * @param type $type * @return type .jpg .gif .webp _thumbs.jpg _Low.mp4 _SD.mp4 _HD.mp4 */ public static function getSourceFile($filename, $type = ".jpg", $includeS3 = false) { global $global, $advancedCustom, $videosPaths, $VideoGetSourceFile; //if(!isValidFormats($type)){ //return array(); //} - - if($type == '_thumbsSmallV2.jpg' && empty($advancedCustom->usePreloadLowResolutionImages)){ - return array('path'=>$global['systemRootPath'].'view/img/loading-gif.png', 'url'=>getCDN().'view/img/loading-gif.png'); + + if ($type == '_thumbsSmallV2.jpg' && empty($advancedCustom->usePreloadLowResolutionImages)) { + return array('path' => $global['systemRootPath'] . 'view/img/loading-gif.png', 'url' => getCDN() . 'view/img/loading-gif.png'); } - + $cacheName = md5($filename . $type . $includeS3); if (0 && isset($VideoGetSourceFile[$cacheName]) && is_array($VideoGetSourceFile[$cacheName])) { if (!preg_match("/token=/", $VideoGetSourceFile[$cacheName]['url'])) { return $VideoGetSourceFile[$cacheName]; } } // check if there is a webp image if ($type === '.gif' && (empty($_SERVER['HTTP_USER_AGENT']) || get_browser_name($_SERVER['HTTP_USER_AGENT']) !== 'Safari')) { $path = self::getStoragePath() . "{$filename}.webp"; if (file_exists($path)) { $type = ".webp"; } } if (empty($videosPaths[$filename][$type][intval($includeS3)])) { $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); if (!empty($aws_s3)) { $aws_s3_obj = $aws_s3->getDataObject(); if (!empty($aws_s3_obj->useS3DirectLink)) { $includeS3 = true; } } elseif (!empty($bb_b2)) { $bb_b2_obj = $bb_b2->getDataObject(); if (!empty($bb_b2_obj->useDirectLink)) { $includeS3 = true; } } elseif (!empty($ftp)) { $includeS3 = true; } $token = ""; $secure = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory'); if ((preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip")) { $vars = array(); if (!empty($secure)) { $vars[] = $secure->getToken($filename); } if (!empty($vars)) { $token = "?" . implode("&", $vars); } } $source = array(); $source['path'] = self::getStoragePath() . "{$filename}{$type}"; if ($type == ".m3u8") { $source['path'] = self::getStoragePath() . "{$filename}/index{$type}"; } $cleanFileName = self::getCleanFilenameFromFile($filename); $video = Video::getVideoFromFileNameLight($cleanFileName); if (empty($video)) { _error_log("Video::getSourceFile($filename, $type, $includeS3) ERROR video not found ($cleanFileName)"); $VideoGetSourceFile[$cacheName] = false; return false; } $canUseCDN = canUseCDN($video['id']); if (!empty($video['sites_id']) && (preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip") && @filesize($source['path']) < 20) { $site = new Sites($video['sites_id']); $siteURL = getCDNOrURL($site->getUrl(), 'CDN_YPTStorage', $video['sites_id']); $source['url'] = "{$siteURL}videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$siteURL}videos/{$filename}/index{$type}{$token}"; } } elseif (!empty($advancedCustom->videosCDN) && $canUseCDN) { $advancedCustom->videosCDN = rtrim($advancedCustom->videosCDN, '/') . '/'; $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}/index{$type}{$token}"; } } else { - $source['url'] = getCDN()."videos/{$filename}{$type}{$token}"; + $source['url'] = getCDN() . "videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { - $source['url'] = getCDN()."videos/{$filename}/index{$type}{$token}"; + $source['url'] = getCDN() . "videos/{$filename}/index{$type}{$token}"; } } /* need it because getDurationFromFile */ if ($includeS3 && ($type == ".mp4" || $type == ".webm" || $type == ".mp3" || $type == ".ogg" || $type == ".pdf" || $type == ".zip")) { if (file_exists($source['path']) && filesize($source['path']) < 1024) { if (!empty($aws_s3)) { $source = $aws_s3->getAddress("{$filename}{$type}"); } elseif (!empty($bb_b2)) { $source = $bb_b2->getAddress("{$filename}{$type}"); } elseif (!empty($ftp)) { $source = $ftp->getAddress("{$filename}{$type}"); } } } if (!file_exists($source['path']) || ($type !== ".m3u8" && !is_dir($source['path']) && (filesize($source['path']) < 1000 && filesize($source['path']) != 10))) { if ($type != "_thumbsV2.jpg" && $type != "_thumbsSmallV2.jpg" && $type != "_portrait_thumbsV2.jpg" && $type != "_portrait_thumbsSmallV2.jpg") { $VideoGetSourceFile[$cacheName] = array('path' => false, 'url' => false); return $VideoGetSourceFile[$cacheName]; } } $videosPaths[$filename][$type][intval($includeS3)] = $source; } else { $source = $videosPaths[$filename][$type][intval($includeS3)]; } if (substr($type, -4) === ".jpg" || substr($type, -4) === ".png" || substr($type, -4) === ".gif" || substr($type, -4) === ".webp") { $x = uniqid(); if (file_exists($source['path'])) { $x = filemtime($source['path']); } elseif (!empty($video)) { $x = strtotime($video['modified']); } $source['url'] .= "?{$x}"; } //ObjectYPT::setCache($name, $source); $VideoGetSourceFile[$cacheName] = $source; return $VideoGetSourceFile[$cacheName]; } public static function getCleanFilenameFromFile($filename) { global $global; if (empty($filename)) { return ""; } $filename = fixPath($filename); $search = array('_Low', '_SD', '_HD', '_thumbsV2', '_thumbsSmallV2', '_thumbsSprit', '_roku', '_portrait', '_portrait_thumbsV2', '_portrait_thumbsSmallV2'); $replace = array('', '', '', '', '', '', '', '', '', ''); if (empty($global['avideo_resolutions']) || !is_array($global['avideo_resolutions'])) { $global['avideo_resolutions'] = array(240, 360, 480, 540, 720, 1080, 1440, 2160); } foreach ($global['avideo_resolutions'] as $value) { $search[] = "_{$value}"; $replace[] = ''; - + $search[] = "res{$value}"; $replace[] = ''; } $cleanName = str_replace($search, $replace, $filename); $path_parts = pathinfo($cleanName); if (!empty($path_parts["extension"]) && $path_parts["extension"] === "m3u8") { preg_match('/videos\/([^\/]+)/', $path_parts["dirname"], $matches); if (!empty($matches[1])) { $path_parts['filename'] = $matches[1]; } } if (empty($path_parts['extension'])) { //_error_log("Video::getCleanFilenameFromFile could not find extension of ".$filename); if (!empty($path_parts['filename'])) { return $path_parts['filename']; } else { return $filename; } } else if (strlen($path_parts['extension']) > 4) { return $cleanName; } else if ($path_parts['filename'] == 'index' && $path_parts['extension'] == 'm3u8') { $clanFileName = str_replace(getVideosDir(), '', $path_parts['dirname']); $parts = explode(DIRECTORY_SEPARATOR, $clanFileName); return $parts[0]; } else { return $path_parts['filename']; } } public static function getSpecificResolution($filename, $desired_resolution) { $filename = self::getCleanFilenameFromFile($filename); $cacheName = "getSpecificResolution($filename)"; $return = ObjectYPT::getCache($cacheName, 0); if (!empty($return)) { return object_to_array($return); } $name0 = "Video:::getSpecificResolution($filename)"; TimeLogStart($name0); $name1 = "Video:::getSpecificResolution::getVideosURL_V2($filename)"; TimeLogStart($name1); $sources = getVideosURL_V2($filename); if (!is_array($sources)) { _error_log("Video:::getSpecificResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources)); return array(); } TimeLogEnd($name1, __LINE__); $return = array(); foreach ($sources as $key => $value) { if ($value['type'] === 'video') { $parts = explode("_", $key); $resolution = intval(@$parts[1]); if (empty($resolution)) { $name2 = "Video:::getSpecificResolution::getResolution({$value["path"]})"; TimeLogStart($name2); $resolution = self::getResolution($value["path"]); TimeLogEnd($name2, __LINE__); } if (!isset($return['resolution']) || $resolution == $desired_resolution) { $return = $value; $return['resolution'] = $resolution; $return['resolution_text'] = getResolutionText($return['resolution']); $return['resolution_label'] = getResolutionLabel($return['resolution']); $return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}"); } } } TimeLogEnd($name0, __LINE__); ObjectYPT::setCache($cacheName, $return); return $return; } public static function getHigestResolution($filename) { global $global; $filename = self::getCleanFilenameFromFile($filename); $cacheName = "getHigestResolution($filename)"; $return = ObjectYPT::getCache($cacheName, 0); if (!empty($return)) { return object_to_array($return); } $name0 = "Video:::getHigestResolution($filename)"; TimeLogStart($name0); $name1 = "Video:::getHigestResolution::getVideosURL_V2($filename)"; TimeLogStart($name1); $sources = getVideosURL_V2($filename); if (!is_array($sources)) { _error_log("Video:::getHigestResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources)); return array(); } TimeLogEnd($name1, __LINE__); $return = array(); foreach ($sources as $key => $value) { if ($value['type'] === 'video') { $parts = explode("_", $key); $resolution = intval(@$parts[1]); if (empty($resolution)) { $name2 = "Video:::getHigestResolution::getResolution({$value["path"]})"; TimeLogStart($name2); $resolution = self::getResolutionFromFilename($value["path"]); // this is faster if ($resolution && empty($global['onlyGetResolutionFromFilename'])) { _error_log("Video:::getHigestResolution:: could not get the resolution from file name, trying a slower method"); $resolution = self::getResolution($value["path"]); } TimeLogEnd($name2, __LINE__); } if (!isset($return['resolution']) || $resolution > $return['resolution']) { $return = $value; $return['resolution'] = $resolution; $return['resolution_text'] = getResolutionText($return['resolution']); $return['resolution_label'] = getResolutionLabel($return['resolution']); $return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}"); } } } TimeLogEnd($name0, __LINE__); ObjectYPT::setCache($cacheName, $return); return $return; } public static function getResolutionFromFilename($filename) { $resolution = false; if (preg_match("/_([0-9]+).(mp4|webm)/i", $filename, $matches)) { if (!empty($matches[1])) { $resolution = intval($matches[1]); } } elseif (preg_match('/res([0-9]+)\/index.m3u8/i', $filename, $matches)) { if (!empty($matches[1])) { $resolution = intval($matches[1]); } } //var_dump($filename, $resolution);exit; return $resolution; } public static function getHigestResolutionVideoMP4Source($filename, $includeS3 = false) { global $global; $types = array('', '_HD', '_SD', '_Low'); $resolutions = $global['avideo_resolutions']; rsort($resolutions); foreach ($resolutions as $value) { $types[] = "_{$value}"; } foreach ($types as $value) { $source = self::getSourceFile($filename, $value . ".mp4", $includeS3); if (!empty($source['url'])) { return $source; } } return false; } public static function getHigherVideoPathFromID($videos_id) { global $global; if (empty($videos_id)) { return false; } $paths = self::getVideosPathsFromID($videos_id); $types = array(0, 2160, 1440, 1080, 720, 'HD', 'SD', 'Low', 540, 480, 360, 240); if (!empty($paths['mp4'])) { foreach ($types as $value) { if (!empty($paths['mp4'][$value])) { if (is_string($paths['mp4'][$value])) { return $paths['mp4'][$value]; } else { return $paths['mp4'][$value]["url"]; } } } } if (!empty($paths['webm'])) { foreach ($types as $value) { if (!empty($paths['webm'][$value])) { if (is_string($paths['webm'][$value])) { return $paths['webm'][$value]; } else { return $paths['webm'][$value]["url"]; } } } } if (!empty($paths['m3u8'])) { if (!empty($paths['m3u8'])) { if (is_string($paths['m3u8']["url"])) { return $paths['m3u8']["url"]; } elseif (is_string($paths['m3u8'][$value])) { return $paths['m3u8'][$value]; } else { return $paths['m3u8'][$value]["url"]; } } } if (!empty($paths['mp3'])) { return $paths['mp3']; } return false; } public static function getVideosPathsFromID($videos_id) { if (empty($videos_id)) { return false; } $video = new Video("", "", $videos_id); return self::getVideosPaths($video->getFilename(), true); } public static function getVideosPaths($filename, $includeS3 = false) { global $global; $types = array('', '_Low', '_SD', '_HD'); foreach ($global['avideo_resolutions'] as $value) { $types[] = "_{$value}"; } $videos = array(); $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (!empty($plugin)) { $videos = VideoHLS::getSourceFile($filename, $includeS3); } foreach ($types as $value) { $source = self::getSourceFile($filename, $value . ".mp4", $includeS3); if (!empty($source['url'])) { $videos['mp4'][str_replace("_", "", $value)] = $source['url']; } } foreach ($types as $value) { $source = self::getSourceFile($filename, $value . ".webm", $includeS3); if (!empty($source['url'])) { $videos['webm'][str_replace("_", "", $value)] = $source['url']; } } $source = self::getSourceFile($filename, ".pdf", $includeS3); if (!empty($source['url'])) { $videos['pdf'] = $source['url']; } $source = self::getSourceFile($filename, ".zip", $includeS3); if (!empty($source['url'])) { $videos['zip'] = $source['url']; } $source = self::getSourceFile($filename, ".mp3", $includeS3); if (!empty($source['url'])) { $videos['mp3'] = $source['url']; } return $videos; } public static function getStoragePath() { global $global; $path = "{$global['systemRootPath']}videos" . DIRECTORY_SEPARATOR; return $path; } public static function getStoragePathFromFileName($filename) { $cleanFileName = self::getCleanFilenameFromFile($filename); $path = self::getStoragePath() . "{$cleanFileName}/"; make_path($path); return $path; } public static function getStoragePathFromVideosId($videos_id) { $v = new Video("", "", $videos_id); return self::getStoragePathFromFileName($v->getFilename()); } public static function getImageFromFilename($filename, $type = "video", $async = false) { global $advancedCustom; // I dont know why but I had to remove it to avoid ERR_RESPONSE_HEADERS_TOO_BIG header_remove('Set-Cookie'); if (empty($advancedCustom->AsyncJobs) && !$async) { return self::getImageFromFilename_($filename, $type); } else { return self::getImageFromFilenameAsync($filename, $type); } } public static function getPoster($videos_id) { $images = self::getImageFromID($videos_id); if (!empty($images->poster)) { return $images->poster; } if (!empty($images->posterPortrait)) { return $images->poster; } return false; } public static function getRokuImage($videos_id) { global $global; $images = self::getImageFromID($videos_id); $imagePath = $images->posterLandscapePath; if (empty($imagePath) || !file_exists($imagePath)) { $imagePath = $images->posterLandscapeThumbs; } if (empty($imagePath) || !file_exists($imagePath)) { $imagePath = $images->poster; } $rokuImage = str_replace(".jpg", "_roku.jpg", $imagePath); if (convertImageToRoku($images->posterLandscapePath, $rokuImage)) { return str_replace($global['systemRootPath'], $global['webSiteRootURL'], $rokuImage); } - return "".getCDN()."view/img/notfound.jpg"; + return "" . getCDN() . "view/img/notfound.jpg"; } public static function clearImageCache($filename, $type = "video") { $cacheFileName = "getImageFromFilename_" . $filename . $type . (get_browser_name() == 'Safari' ? "s" : ""); return ObjectYPT::deleteCache($cacheFileName); } public static function getImageFromFilename_($filename, $type = "video") { if (empty($filename)) { return array(); } global $_getImageFromFilename_; if (empty($_getImageFromFilename_)) { $_getImageFromFilename_ = array(); } $cacheFileName = "getImageFromFilename_" . $filename . $type . (get_browser_name() == 'Safari' ? "s" : ""); if (!empty($_getImageFromFilename_[$cacheFileName])) { $obj = $_getImageFromFilename_[$cacheFileName]; } else { $cache = ObjectYPT::getCache($cacheFileName, 0); if (!empty($cache)) { return $cache; } global $global, $advancedCustom; /* $name = "getImageFromFilename_{$filename}{$type}_"; $cached = ObjectYPT::getCache($name, 86400);//one day if(!empty($cached)){ return $cached; } * */ $obj = new stdClass(); $gifSource = self::getSourceFile($filename, ".gif"); $gifPortraitSource = self::getSourceFile($filename, "_portrait.gif"); $jpegSource = self::getSourceFile($filename, ".jpg"); $jpegPortraitSource = self::getSourceFile($filename, "_portrait.jpg"); $jpegPortraitThumbs = self::getSourceFile($filename, "_portrait_thumbsV2.jpg"); $jpegPortraitThumbsSmall = self::getSourceFile($filename, "_portrait_thumbsSmallV2.jpg"); $thumbsSource = self::getSourceFile($filename, "_thumbsV2.jpg"); $thumbsSmallSource = self::getSourceFile($filename, "_thumbsSmallV2.jpg"); $spectrumSource = self::getSourceFile($filename, "_spectrum.jpg"); if (empty($jpegSource)) { return array(); } $obj->poster = $jpegSource['url']; $obj->posterPortrait = $jpegPortraitSource['url']; $obj->posterPortraitPath = $jpegPortraitSource['path']; $obj->posterPortraitThumbs = $jpegPortraitThumbs['url']; $obj->posterPortraitThumbsSmall = $jpegPortraitThumbsSmall['url']; $obj->thumbsGif = $gifSource['url']; $obj->gifPortrait = $gifPortraitSource['url']; $obj->thumbsJpg = $thumbsSource['url']; $obj->thumbsJpgSmall = $thumbsSmallSource['url']; $obj->spectrumSource = $spectrumSource['url']; $obj->posterLandscape = $jpegSource['url']; $obj->posterLandscapePath = $jpegSource['path']; $obj->posterLandscapeThumbs = $thumbsSource['url']; $obj->posterLandscapeThumbsSmall = $thumbsSmallSource['url']; if (file_exists($gifSource['path'])) { $obj->thumbsGif = $gifSource['url']; } if (file_exists($jpegPortraitSource['path'])) { // create thumbs if (!file_exists($jpegPortraitThumbs['path']) && filesize($jpegPortraitSource['path']) > 1024) { _error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbs['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait); } else { im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait); } } // create thumbs if (!file_exists($jpegPortraitThumbsSmall['path']) && filesize($jpegPortraitSource['path']) > 1024) { _error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbsSmall['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait); } else { im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait, 5); } } } else { if ($type == "article") { - $obj->posterPortrait = "".getCDN()."view/img/article_portrait.png"; + $obj->posterPortrait = "" . getCDN() . "view/img/article_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/article_portrait.png"; - $obj->posterPortraitThumbs = "".getCDN()."view/img/article_portrait.png"; - $obj->posterPortraitThumbsSmall = "".getCDN()."view/img/article_portrait.png"; + $obj->posterPortraitThumbs = "" . getCDN() . "view/img/article_portrait.png"; + $obj->posterPortraitThumbsSmall = "" . getCDN() . "view/img/article_portrait.png"; } elseif ($type == "pdf") { - $obj->posterPortrait = "".getCDN()."view/img/pdf_portrait.png"; + $obj->posterPortrait = "" . getCDN() . "view/img/pdf_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/pdf_portrait.png"; - $obj->posterPortraitThumbs = "".getCDN()."view/img/pdf_portrait.png"; - $obj->posterPortraitThumbsSmall = "".getCDN()."view/img/pdf_portrait.png"; + $obj->posterPortraitThumbs = "" . getCDN() . "view/img/pdf_portrait.png"; + $obj->posterPortraitThumbsSmall = "" . getCDN() . "view/img/pdf_portrait.png"; } /* else if ($type == "image") { $obj->posterPortrait = "".getCDN()."view/img/image_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/image_portrait.png"; $obj->posterPortraitThumbs = "".getCDN()."view/img/image_portrait.png"; $obj->posterPortraitThumbsSmall = "".getCDN()."view/img/image_portrait.png"; } */ elseif ($type == "zip") { - $obj->posterPortrait = "".getCDN()."view/img/zip_portrait.png"; + $obj->posterPortrait = "" . getCDN() . "view/img/zip_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/zip_portrait.png"; - $obj->posterPortraitThumbs = "".getCDN()."view/img/zip_portrait.png"; - $obj->posterPortraitThumbsSmall = "".getCDN()."view/img/zip_portrait.png"; + $obj->posterPortraitThumbs = "" . getCDN() . "view/img/zip_portrait.png"; + $obj->posterPortraitThumbsSmall = "" . getCDN() . "view/img/zip_portrait.png"; } else { - $obj->posterPortrait = "".getCDN()."view/img/notfound_portrait.jpg"; + $obj->posterPortrait = "" . getCDN() . "view/img/notfound_portrait.jpg"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/notfound_portrait.png"; - $obj->posterPortraitThumbs = "".getCDN()."view/img/notfound_portrait.jpg"; - $obj->posterPortraitThumbsSmall = "".getCDN()."view/img/notfound_portrait.jpg"; + $obj->posterPortraitThumbs = "" . getCDN() . "view/img/notfound_portrait.jpg"; + $obj->posterPortraitThumbsSmall = "" . getCDN() . "view/img/notfound_portrait.jpg"; } } if (file_exists($jpegSource['path'])) { $obj->poster = $jpegSource['url']; $obj->thumbsJpg = $thumbsSource['url']; // create thumbs if (!file_exists($thumbsSource['path']) && filesize($jpegSource['path']) > 1024) { _error_log("Resize JPG {$jpegSource['path']}, {$thumbsSource['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); } else { im_resizeV2($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); } } // create thumbs if (!file_exists($thumbsSmallSource['path']) && filesize($jpegSource['path']) > 1024) { _error_log("Resize Small JPG {$jpegSource['path']}, {$thumbsSmallSource['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape); } else { im_resizeV2($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape, 5); } } } else { if ($type == "article") { - $obj->poster = "".getCDN()."view/img/article.png"; - $obj->thumbsJpg = "".getCDN()."view/img/article.png"; - $obj->thumbsJpgSmall = "".getCDN()."view/img/article.png"; + $obj->poster = "" . getCDN() . "view/img/article.png"; + $obj->thumbsJpg = "" . getCDN() . "view/img/article.png"; + $obj->thumbsJpgSmall = "" . getCDN() . "view/img/article.png"; } elseif ($type == "pdf") { - $obj->poster = "".getCDN()."view/img/pdf.png"; - $obj->thumbsJpg = "".getCDN()."view/img/pdf.png"; - $obj->thumbsJpgSmall = "".getCDN()."view/img/pdf.png"; + $obj->poster = "" . getCDN() . "view/img/pdf.png"; + $obj->thumbsJpg = "" . getCDN() . "view/img/pdf.png"; + $obj->thumbsJpgSmall = "" . getCDN() . "view/img/pdf.png"; } elseif ($type == "image") { - $obj->poster = "".getCDN()."view/img/image.png"; - $obj->thumbsJpg = "".getCDN()."view/img/image.png"; - $obj->thumbsJpgSmall = "".getCDN()."view/img/image.png"; + $obj->poster = "" . getCDN() . "view/img/image.png"; + $obj->thumbsJpg = "" . getCDN() . "view/img/image.png"; + $obj->thumbsJpgSmall = "" . getCDN() . "view/img/image.png"; } elseif ($type == "zip") { - $obj->poster = "".getCDN()."view/img/zip.png"; - $obj->thumbsJpg = "".getCDN()."view/img/zip.png"; - $obj->thumbsJpgSmall = "".getCDN()."view/img/zip.png"; + $obj->poster = "" . getCDN() . "view/img/zip.png"; + $obj->thumbsJpg = "" . getCDN() . "view/img/zip.png"; + $obj->thumbsJpgSmall = "" . getCDN() . "view/img/zip.png"; } elseif (($type !== "audio") && ($type !== "linkAudio")) { if (file_exists($spectrumSource['path'])) { $obj->poster = $spectrumSource['url']; $obj->thumbsJpg = $spectrumSource['url']; $obj->thumbsJpgSmall = $spectrumSource['url']; } else { - $obj->poster = "".getCDN()."view/img/notfound.jpg"; - $obj->thumbsJpg = "".getCDN()."view/img/notfoundThumbs.jpg"; - $obj->thumbsJpgSmall = "".getCDN()."view/img/notfoundThumbsSmall.jpg"; + $obj->poster = "" . getCDN() . "view/img/notfound.jpg"; + $obj->thumbsJpg = "" . getCDN() . "view/img/notfoundThumbs.jpg"; + $obj->thumbsJpgSmall = "" . getCDN() . "view/img/notfoundThumbsSmall.jpg"; } } else { - $obj->poster = "".getCDN()."view/img/audio_wave.jpg"; - $obj->thumbsJpg = "".getCDN()."view/img/audio_waveThumbs.jpg"; - $obj->thumbsJpgSmall = "".getCDN()."view/img/audio_waveThumbsSmall.jpg"; + $obj->poster = "" . getCDN() . "view/img/audio_wave.jpg"; + $obj->thumbsJpg = "" . getCDN() . "view/img/audio_waveThumbs.jpg"; + $obj->thumbsJpgSmall = "" . getCDN() . "view/img/audio_waveThumbsSmall.jpg"; } } if (empty($obj->thumbsJpg)) { $obj->thumbsJpg = $obj->poster; } if (empty($obj->thumbsJpgSmall)) { $obj->thumbsJpgSmall = $obj->poster; } //ObjectYPT::setCache($name, $obj); if (!empty($advancedCustom->disableAnimatedGif)) { $obj->thumbsGif = false; } ObjectYPT::setCache($cacheFileName, $obj); $_getImageFromFilename_[$cacheFileName] = $obj; } return $obj; } public static function getImageFromFilenameAsync($filename, $type = "video") { global $global, $advancedCustom; $return = array(); $path = getCacheDir() . "getImageFromFilenameAsync/"; make_path($path); $cacheFileName = "{$path}_{$filename}_{$type}"; if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getImageFromFilename_($filename, $type); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = _json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getImageFromFilenameAsync.php' '$filename' '$type' '{$cacheFileName}'"); //_error_log("getImageFromFilenameAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } public static function getImageFromID($videos_id, $type = "video") { $video = new Video("", "", $videos_id); return self::getImageFromFilename($video->getFilename()); } public function getViews_count() { return intval($this->views_count); } public static function get_clean_title($videos_id) { global $global; $sql = "SELECT * FROM videos WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { if ($videoRow != false) { return $videoRow['clean_title']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } public static function get_id_from_clean_title($clean_title) { global $global; $sql = "SELECT * FROM videos WHERE clean_title = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($clean_title)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { if ($videoRow != false) { return $videoRow['id']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } public function getChannelName() { return User::_getChannelName($this->getUsers_id()); } public function getChannelLink() { return User::getChannelLink($this->getUsers_id()); } /** * * @global type $global * @param type $videos_id * @param type $clean_title * @param type $embed * @param type $type URLFriendly or permalink * @return String a web link */ public static function getLinkToVideo($videos_id, $clean_title = "", $embed = false, $type = "URLFriendly", $get = array()) { if (!empty($_GET['evideo'])) { $v = self::decodeEvideo(); if (!empty($v['video']['videoLink'])) { if ($embed) { return parseVideos($v['video']['videoLink']); } else { return $v['video']['videoLink']; } } } global $global, $advancedCustomUser, $advancedCustom; if (empty($videos_id) && !empty($clean_title)) { $videos_id = self::get_id_from_clean_title($clean_title); } $video = new Video("", "", $videos_id); if ($advancedCustomUser->addChannelNameOnLinks) { $get['channelName'] = $video->getChannelName(); } unset($get['v']); unset($get['videoName']); unset($get['videoName']); unset($get['isMediaPlaySite']); unset($get['parentsOnly']); $get_http = http_build_query($get); if (empty($get_http)) { $get_http = ""; } else { $get_http = "?{$get_http}"; } if ($type == "URLFriendly") { $cat = ""; if (!empty($_GET['catName'])) { $cat = "cat/{$_GET['catName']}/"; } if (empty($clean_title)) { $clean_title = $video->getClean_title(); } $clean_title = urlencode($clean_title); $subDir = "video"; $subEmbedDir = "videoEmbed"; if ($video->getType() == 'article') { $subDir = "article"; $subEmbedDir = "articleEmbed"; } - if(!empty($advancedCustom->makeVideosIDHarderToGuess)){ - $encryptedVideos_id = '.'.idToHash($videos_id); + if (!empty($advancedCustom->makeVideosIDHarderToGuess)) { + $encryptedVideos_id = '.' . idToHash($videos_id); $videos_id = $encryptedVideos_id; } if ($embed) { if (empty($advancedCustom->useVideoIDOnSEOLinks)) { return "{$global['webSiteRootURL']}{$subEmbedDir}/{$clean_title}{$get_http}"; } else { return "{$global['webSiteRootURL']}{$subEmbedDir}/{$videos_id}/{$clean_title}{$get_http}"; } } else { if (empty($advancedCustom->useVideoIDOnSEOLinks)) { return "{$global['webSiteRootURL']}{$cat}{$subDir}/{$clean_title}{$get_http}"; } else { return "{$global['webSiteRootURL']}{$subDir}/{$videos_id}/{$clean_title}{$get_http}"; } } } else { - if(!empty($advancedCustom->makeVideosIDHarderToGuess)){ - $encryptedVideos_id = '.'.idToHash($videos_id); + if (!empty($advancedCustom->makeVideosIDHarderToGuess)) { + $encryptedVideos_id = '.' . idToHash($videos_id); $videos_id = $encryptedVideos_id; } if ($embed) { return "{$global['webSiteRootURL']}vEmbed/{$videos_id}{$get_http}"; } else { return "{$global['webSiteRootURL']}v/{$videos_id}{$get_http}"; } } } public static function getPermaLink($videos_id, $embed = false, $get = array()) { return self::getLinkToVideo($videos_id, "", $embed, "permalink", $get); } public static function getURLFriendly($videos_id, $embed = false, $get = array()) { return self::getLinkToVideo($videos_id, "", $embed, "URLFriendly", $get); } public static function getPermaLinkFromCleanTitle($clean_title, $embed = false, $get = array()) { return self::getLinkToVideo("", $clean_title, $embed, "permalink", $get); } public static function getURLFriendlyFromCleanTitle($clean_title, $embed = false, $get = array()) { return self::getLinkToVideo("", $clean_title, $embed, "URLFriendly", $get); } public static function getLink($videos_id, $clean_title, $embed = false, $get = array()) { global $advancedCustom; if (!empty($advancedCustom->usePermalinks)) { $type = "permalink"; } else { $type = "URLFriendly"; } return self::getLinkToVideo($videos_id, $clean_title, $embed, $type, $get); } public static function getTotalVideosThumbsUpFromUser($users_id, $startDate, $endDate) { global $global; $sql = "SELECT id from videos WHERE users_id = ? "; $res = sqlDAL::readSql($sql, "i", array($users_id)); $videoRows = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $r = array('thumbsUp' => 0, 'thumbsDown' => 0); if ($res != false) { foreach ($videoRows as $row) { $values = array($row['id']); $format = "i"; $sql = "SELECT id from likes WHERE videos_id = ? AND `like` = 1 "; if (!empty($startDate)) { $sql .= " AND `created` >= ? "; $format .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `created` <= ? "; $format .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); $r['thumbsUp'] += $countRow; $format = ""; $values = array(); $sql = "SELECT id from likes WHERE videos_id = {$row['id']} AND `like` = -1 "; if (!empty($startDate)) { $sql .= " AND `created` >= ? "; $format .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `created` <= ? "; $format .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); $r['thumbsDown'] += $countRow; } } return $r; } public static function deleteThumbs($filename, $doNotDeleteSprit = false) { if (empty($filename)) { return false; } global $global; $filePath = Video::getStoragePath() . "{$filename}"; // Streamlined for less coding space. $files = glob("{$filePath}*_thumbs*.jpg"); foreach ($files as $file) { if (file_exists($file)) { if ($doNotDeleteSprit && strpos($file, '_thumbsSprit.jpg') !== false) { continue; } @unlink($file); } } ObjectYPT::deleteCache($filename); ObjectYPT::deleteCache($filename . "article"); ObjectYPT::deleteCache($filename . "pdf"); ObjectYPT::deleteCache($filename . "video"); Video::clearImageCache($filename); Video::clearImageCache($filename, "article"); Video::clearImageCache($filename, "pdf"); Video::clearImageCache($filename, "audio"); clearVideosURL($filename); return true; } public static function clearCache($videos_id) { _error_log("Video:clearCache($videos_id)"); $video = new Video("", "", $videos_id); $filename = $video->getFilename(); if (empty($filename)) { _error_log("Video:clearCache filename not found"); return false; } self::deleteThumbs($filename, true); ObjectYPT::deleteCache("otherInfo{$videos_id}"); ObjectYPT::deleteCache($filename); ObjectYPT::deleteCache("getVideosURL_V2$filename"); ObjectYPT::deleteCache($filename . "article"); ObjectYPT::deleteCache($filename . "pdf"); ObjectYPT::deleteCache($filename . "video"); ObjectYPT::deleteCache(md5($filename . ".m3u8")); ObjectYPT::deleteCache(md5($filename . ".mp4")); ObjectYPT::deleteCache(md5($filename . ".m3u81")); ObjectYPT::deleteCache(md5($filename . ".mp41")); ObjectYPT::deleteCache("getSourceFile($filename)1"); ObjectYPT::deleteCache("getSourceFile($filename)0"); Video::clearImageCache($filename); Video::clearImageCache($filename, "article"); Video::clearImageCache($filename, "pdf"); Video::clearImageCache($filename, "audio"); Video::deleteTagsAsync($videos_id); clearVideosURL($filename); AVideoPlugin::deleteVideoTags($videos_id); ObjectYPT::setLastDeleteALLCacheTime(); return true; } public static function clearCacheFromFilename($fileName) { _error_log("Video:clearCacheFromFilename($fileName)"); $video = self::getVideoFromFileNameLight($fileName); if (empty($video['id'])) { return false; } return self::clearCache($video['id']); } public static function getVideoPogress($videos_id, $users_id = 0) { if (empty($users_id)) { if (!User::isLogged()) { return 0; } $users_id = User::getId(); } return VideoStatistic::getLastVideoTimeFromVideo($videos_id, $users_id); } public static function getLastVideoTimePosition($videos_id, $users_id = 0) { return self::getVideoPogress($videos_id, $users_id); } public static function getVideoPogressPercent($videos_id, $users_id = 0) { $lastVideoTime = self::getVideoPogress($videos_id, $users_id); if (empty($lastVideoTime)) { return array('percent' => 0, 'lastVideoTime' => 0); } // start incremental search and save $sql = "SELECT duration FROM `videos` WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $row = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (empty($row) || empty($row['duration'])) { return array('percent' => 0, 'lastVideoTime' => 0); } $duration = parseDurationToSeconds($row['duration']); if (empty($duration)) { return array('percent' => 0, 'lastVideoTime' => 0); } if ($lastVideoTime > $duration) { return array('percent' => 100, 'lastVideoTime' => $lastVideoTime); } return array('percent' => ($lastVideoTime / $duration) * 100, 'lastVideoTime' => $lastVideoTime); } public function getRrating() { return $this->rrating; } public function setRrating($rrating) { $rrating = strtolower($rrating); if (!in_array($rrating, self::$rratingOptions)) { $rrating = ''; } AVideoPlugin::onVideoSetRrating($this->id, $this->rrating, $rrating); $this->rrating = $rrating; } public static function getVideoType($filename) { global $_getVideoType; if (!isset($_getVideoType)) { $_getVideoType = array(); } if (isset($_getVideoType[$filename])) { return $_getVideoType[$filename]; } $obj = new stdClass(); $paths = self::getVideosPaths($filename); $obj->mp4 = !empty($paths['mp4']) ? true : false; $obj->webm = !empty($paths['webm']) ? true : false; $obj->m3u8 = !empty($paths['m3u8']) ? true : false; $obj->pdf = !empty($paths['pdf']) ? true : false; $obj->mp3 = !empty($paths['mp3']) ? true : false; $_getVideoType[$filename] = $obj; return $obj; } public static function getVideoTypeLabels($filename) { $obj = self::getVideoType($filename); $labels = ""; if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) { return 'Other'; } if ($obj->mp4) { $labels .= 'MP4'; } if ($obj->webm) { $labels .= 'Webm'; } if ($obj->m3u8) { $labels .= 'HLS'; } if ($obj->pdf) { $labels .= 'PDF'; } if ($obj->mp3) { $labels .= 'MP3'; } return $labels; } /** * Based on Roku Type * @param type $filename * @return string */ public static function getVideoTypeText($filename) { $obj = self::getVideoType($filename); $labels = ""; if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) { return __('Other'); } if ($obj->mp4) { return 'MP4'; } if ($obj->webm) { return 'WEBM'; } if ($obj->m3u8) { return 'HLS'; } if ($obj->pdf) { return 'PDF'; } if ($obj->mp3) { return 'MP3'; } return $labels; } public static function isPublic($videos_id) { // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { return true; } return false; } public static function userGroupAndVideoGroupMatch($users_id, $videos_id) { if (empty($videos_id)) { return false; } $ppv = AVideoPlugin::loadPluginIfEnabled("PayPerView"); if ($ppv) { $ppv->userCanWatchVideo($users_id, $videos_id); } // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { return true; } if (empty($users_id)) { return false; } $rowsUser = UserGroups::getUserGroups(User::getId()); if (empty($rowsUser)) { return false; } foreach ($rows as $value) { foreach ($rowsUser as $value2) { if ($value['id'] === $value2['id']) { return true; } } } return false; } public function getExternalOptions() { return $this->externalOptions; } public function setExternalOptions($externalOptions) { AVideoPlugin::onVideoSetExternalOptions($this->id, $this->externalOptions, $externalOptions); $this->externalOptions = $externalOptions; } public function setVideoStartSeconds($videoStartSeconds) { $externalOptions = _json_decode($this->getExternalOptions()); AVideoPlugin::onVideoSetVideoStartSeconds($this->id, $this->videoStartSeconds, $videoStartSeconds); $externalOptions->videoStartSeconds = $videoStartSeconds; $this->setExternalOptions(json_encode($externalOptions)); } + public function setVideoEmbedWhitelist($embedWhitelist) { + $externalOptions = _json_decode($this->getExternalOptions()); + $externalOptions->embedWhitelist = $embedWhitelist; + $this->setExternalOptions(json_encode($externalOptions)); + } + public function getSerie_playlists_id() { return $this->serie_playlists_id; } public function setSerie_playlists_id($serie_playlists_id) { AVideoPlugin::onVideoSetSerie_playlists_id($this->id, $this->serie_playlists_id, $serie_playlists_id); $this->serie_playlists_id = $serie_playlists_id; } public static function getVideoFromSeriePlayListsId($serie_playlists_id) { global $global, $config; $serie_playlists_id = intval($serie_playlists_id); $sql = "SELECT * FROM videos WHERE serie_playlists_id = '$serie_playlists_id' LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } /** * if will show likes, comments, share, etc * @return boolean */ public static function showYoutubeModeOptions() { global $video; if (!empty($_GET['evideo'])) { $v = self::decodeEvideo(); if (empty($v['video']['views_count'])) { return false; } else { return true; } } if (empty($video) || $video['type'] === 'notfound') { return false; } return true; } public static function decodeEvideo() { $evideo = false; if (!empty($_GET['evideo'])) { $evideo = _json_decode(decryptString($_GET['evideo'])); } $video = array(); if (!empty($evideo)) { $video['id'] = 0; $video['type'] = 'embed'; $video['rotation'] = 0; $video['videoLink'] = $evideo->videoLink; $video['title'] = $evideo->title; $video['clean_title'] = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\] ]+/', '-', trim(strtolower(cleanString($evideo->title)))); if (empty($evideo->description) && !empty($evideo->videos_id)) { $divId = uniqid(); $video['description'] = '
'; } else { $video['description'] = @$evideo->description; } $video['duration'] = @$evideo->duration; $video['creator'] = @$evideo->creator; $video['likes'] = ""; $video['dislikes'] = ""; $video['category'] = "embed"; $video['views_count'] = intval(@$evideo->views_count); } return array('evideo' => $evideo, 'video' => $video); } private static function getBlockedUsersIdsArray($users_id = 0) { if (empty($users_id)) { $users_id = intval(User::getId()); } if (empty($users_id)) { return array(); } if (!User::isLogged()) { return array(); } $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { return array(); } return ReportVideo::getAllReportedUsersIdFromUser($users_id); } public static function getIncludeType($video) { $vType = $video['type']; if ($vType == 'linkVideo') { if (!preg_match('/m3u8/', $video['videoLink'])) { $vType = isHTMLPage($video['videoLink']) ? 'embed' : 'video'; } else { $vType = 'video'; } } elseif ($vType == 'live') { $vType = '../../plugin/Live/view/liveVideo'; } elseif ($vType == 'linkAudio') { $vType = 'audio'; } if (!in_array($vType, Video::$typeOptions)) { $vType = 'video'; } return $vType; } private static function getFullTextSearch($columnsArray, $search, $connection = "OR") { global $global; $search = $global['mysqli']->real_escape_string(xss_esc($search)); if (empty($columnsArray) || empty($search)) { return ""; } $sql = "("; $matches = array(); foreach ($columnsArray as $value) { $matches[] = " (MATCH({$value}) AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)) "; } $sql .= implode(" OR ", $matches); $sql .= ")"; return "{$connection} {$sql}"; } public static function getChangeVideoStatusButton($videos_id) { $video = new Video('', '', $videos_id); $status = $video->getStatus(); $activeBtn = ''; $inactiveBtn = ''; $unlistedBtn = ''; return "{$activeBtn}{$inactiveBtn}{$unlistedBtn}"; } } } // just to convert permalink into clean_title if (!empty($_GET['v']) && empty($_GET['videoName'])) { $_GET['videoName'] = Video::get_clean_title($_GET['v']); -} +} \ No newline at end of file diff --git a/plugin/ADs/pluginMenu.html b/plugin/ADs/pluginMenu.html index b8460b742..b71ce8b23 100644 --- a/plugin/ADs/pluginMenu.html +++ b/plugin/ADs/pluginMenu.html @@ -1 +1 @@ - Edit \ No newline at end of file + \ No newline at end of file diff --git a/plugin/API/info.php b/plugin/API/info.php index d437022b3..583ee960a 100644 --- a/plugin/API/info.php +++ b/plugin/API/info.php @@ -1,113 +1,113 @@ $method_name) { if (!preg_match("/(get|set)_api_(.*)/", $method_name, $matches)) { unset($class_methods[$key]); } } usort($class_methods, function ($a, $b) { if (!preg_match("/(get|set)_api_(.*)/", $a, $matchesA)) { return 0; } if (!preg_match("/(get|set)_api_(.*)/", $b, $matchesB)) { return 0; } return strcasecmp($matchesA[2], $matchesB[2]); }); ?> -
+
diff --git a/plugin/API/pluginMenu.html b/plugin/API/pluginMenu.html index 04e3bde50..607c5f661 100644 --- a/plugin/API/pluginMenu.html +++ b/plugin/API/pluginMenu.html @@ -1 +1 @@ - Info \ No newline at end of file + \ No newline at end of file diff --git a/plugin/AVideoPlugin.php b/plugin/AVideoPlugin.php index b29beeaf3..f184b064e 100644 --- a/plugin/AVideoPlugin.php +++ b/plugin/AVideoPlugin.php @@ -1,2050 +1,2074 @@ $timeLimit) { _error_log("The plugin [{$pluginName}] takes {$total_time} seconds to complete. URL: " . getSelfURI() . " IP: " . getRealIpAddr(), AVideoLog::$WARNING); } } public static function addRoutes() { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->addRoutes(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return false; } public static function addView($videos_id, $total) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->addView($videos_id, $total); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return false; } public static function getHeadCode() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getHeadCode(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getChartTabs() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { if (method_exists($p, 'getChartTabs')) { $str .= $p->getChartTabs(); } else { $checkStr = $p->getChartContent(); if (!empty($checkStr)) { $str .= '
  • ' . $p->getName() . '
  • '; } } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getChartContent() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $checkStr = $p->getChartContent(); if (!empty($checkStr)) { $str .= '
    ' . $checkStr . '
    '; } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getGallerySection() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getGallerySection(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getHelpToc() { $plugins = Plugin::getAllEnabled(); $str = "

    " . __("Table of content") . "

    "; } public static function getHelp() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $t = $p->getHelp(); $str .= $t; if (!empty($t)) { $str .= "
    "; } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getFooterCode() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= PHP_EOL."".PHP_EOL; $str .= $p->getFooterCode(); $str .= PHP_EOL."".PHP_EOL; } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getJSFiles() { $plugins = Plugin::getAllEnabled(); $allFiles = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $js = $p->getJSFiles(); if (is_array($js)) { $allFiles = array_merge($allFiles, $js); } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $allFiles; } public static function getCSSFiles() { $plugins = Plugin::getAllEnabled(); $allFiles = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $allFiles = array_merge($allFiles, $p->getCSSFiles()); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $allFiles; } public static function getHTMLBody() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getHTMLBody(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getHTMLMenuLeft() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getHTMLMenuLeft(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getHTMLMenuRight() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getHTMLMenuRight(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getFirstPage() { return static::getEnabledFirstPage(); } public static function getEnabledFirstPage() { $plugins = Plugin::getAllEnabled(); $firstPage = false; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (!is_object($p)) { continue; } $fp = $p->getFirstPage(); if (!empty($fp)) { $firstPage = $fp; } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $firstPage; } static function loadPlugin($name, $forceReload=false) { global $global, $pluginIsLoaded; if (empty($pluginIsLoaded)) { $pluginIsLoaded = array(); } $loadPluginFile = "{$global['systemRootPath']}plugin/{$name}/{$name}.php"; // need to add dechex because some times it return an negative value and make it fails on javascript playlists if (!isset($pluginIsLoaded[$name]) && empty($forceReload)) { $pluginIsLoaded[$name] = false; if (file_exists($loadPluginFile)) { require_once $loadPluginFile; if (class_exists($name)) { $code = "\$p = new {$name}();"; eval($code); if (is_object($p)) { $pluginIsLoaded[$name] = $p; } else { _error_log("[loadPlugin] eval failed for plugin ($name) code ($code) code result ($codeResult) included file $loadPluginFile", AVideoLog::$ERROR); } } } } return $pluginIsLoaded[$name]; } static function loadPluginIfEnabled($name) { $p = static::loadPlugin($name); if ($p) { $uuid = $p->getUUID(); if (static::isEnabled($uuid)) { return $p; } } return false; } static function isPluginTablesInstalled($name, $installIt = false) { global $global, $isPluginTablesInstalled; $name = self::fixName($name); $installSQLFile = "{$global['systemRootPath']}plugin/{$name}/install/install.sql"; if (isset($isPluginTablesInstalled[$installSQLFile])) { return $isPluginTablesInstalled[$installSQLFile]; } //_error_log("isPluginTablesInstalled: Check for {$installSQLFile}"); if (!file_exists($installSQLFile)) { $isPluginTablesInstalled[$installSQLFile] = true; return $isPluginTablesInstalled[$installSQLFile]; } $lines = file($installSQLFile); foreach ($lines as $line) { $pattern1 = "/CREATE TABLE IF NOT EXISTS `?([a-z0-9_]+)[` (]?/i"; $pattern2 = "/CREATE TABLE[^`]+`?([a-z0-9_]+)[` (]?/i"; if (preg_match($pattern1, $line, $matches)) { if (!empty($matches[1])) { //_error_log("isPluginTablesInstalled: Found ({$matches[1]})"); if (!ObjectYPT::isTableInstalled($matches[1])) { //_error_log("isPluginTablesInstalled: ({$matches[1]}) is NOT installed"); if ($installIt) { sqlDAL::executeFile($installSQLFile); return self::isPluginTablesInstalled($name); } else { //_error_log("isPluginTablesInstalled: You need to install table {$matches[1]} for the plugin ({$name})", AVideoLog::$ERROR); $isPluginTablesInstalled[$installSQLFile] = false; return $isPluginTablesInstalled[$installSQLFile]; } }else{ //_error_log("isPluginTablesInstalled: ({$matches[1]}) is installed"); } } } else if (preg_match($pattern2, $line, $matches)) { if (!empty($matches[1])) { if (!ObjectYPT::isTableInstalled($matches[1])) { _error_log("You need to install table {$matches[1]} for the plugin ({$name})", AVideoLog::$ERROR); $isPluginTablesInstalled[$installSQLFile] = false; return $isPluginTablesInstalled[$installSQLFile]; } } } } $isPluginTablesInstalled[$installSQLFile] = true; return $isPluginTablesInstalled[$installSQLFile]; } static function getObjectData($name) { return self::getDataObject($name); } static function getDataObject($name) { global $pluginGetDataObject; if (!isset($pluginGetDataObject)) { $pluginGetDataObject = array(); } if (!empty($pluginGetDataObject[$name])) { return $pluginGetDataObject[$name]; } $p = static::loadPlugin($name); if ($p) { $pluginGetDataObject[$name] = $p->getDataObject(); return $pluginGetDataObject[$name]; } return false; } static function getObjectDataIfEnabled($name) { return self::getDataObjectIfEnabled($name); } static function getDataObjectIfEnabled($name) { global $_getDataObjectIfEnabled; if(!isset($_getDataObjectIfEnabled)){ $_getDataObjectIfEnabled = array(); } if(isset($_getDataObjectIfEnabled[$name])){ return $_getDataObjectIfEnabled[$name]; } $p = static::loadPlugin($name); if ($p) { $uuid = $p->getUUID(); if (static::isEnabled($uuid)) { $_getDataObjectIfEnabled[$name] = static::getObjectData($name); return $_getDataObjectIfEnabled[$name]; } } $_getDataObjectIfEnabled[$name] = false; return $_getDataObjectIfEnabled[$name]; } static function xsendfilePreVideoPlay() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->xsendfilePreVideoPlay(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } static function getVideosManagerListButton() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getVideosManagerListButton(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } static function getVideosManagerListButtonTitle() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getVideosManagerListButtonTitle(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } static function getUsersManagerListButton() { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getUsersManagerListButton(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } static function getWatchActionButton($videos_id) { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getWatchActionButton($videos_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } static function getNetflixActionButton($videos_id) { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getNetflixActionButton($videos_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } static function getGalleryActionButton($videos_id) { $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getGalleryActionButton($videos_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function isEnabled($uuid) { return !empty(Plugin::getEnabled($uuid)); } public static function exists($name) { global $global; $name = self::fixName($name); $filename = "{$global['systemRootPath']}plugin/{$name}/{$name}.php"; return file_exists($filename); } static function isEnabledByName($name) { global $isPluginEnabledByName; if (empty($isPluginEnabledByName)) { $isPluginEnabledByName = array(); } if (isset($isPluginEnabledByName[$name])) { return $isPluginEnabledByName[$name]; } $p = static::loadPluginIfEnabled($name); $isPluginEnabledByName[$name] = !empty($p); return $isPluginEnabledByName[$name]; } static function getLogin() { $plugins = Plugin::getAllEnabled(); $logins = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $l = $p->getLogin(); if (is_string($l) && file_exists($l)) { // it is a login form $logins[] = $l; } else if (!empty($l->type)) { // it is a hybridauth $logins[] = array('parameters' => $l, 'loginObject' => $p); } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $logins; } public static function getStart() { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { //self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getStart(); } //self::YPTend("{$value['dirName']}::".__FUNCTION__); } } public static function getEnd() { $plugins = Plugin::getAllEnabled(); usort($plugins, function($a, $b) { if($a['name'] == 'Cache'){ return 1; }else if($b['name'] == 'Cache'){ return -1; } return 0; }); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getEnd(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function afterVideoJS() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->afterVideoJS(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function afterNewVideo($videos_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->afterNewVideo($videos_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function afterDonation($from_users_id, $how_much, $videos_id, $users_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->afterDonation($from_users_id, $how_much, $videos_id, $users_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function afterNewComment($comments_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->afterNewComment($comments_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function afterNewResponse($comments_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->afterNewResponse($comments_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function getChannelButton() { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getChannelButton(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function getVideoManagerButton() { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getVideoManagerButton(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function getLivePanel() { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getLivePanel(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function getModeYouTube($videos_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getModeYouTube($videos_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } + + public function getModeLive($key) { + $plugins = Plugin::getAllEnabled(); + foreach ($plugins as $value) { + self::YPTstart(); + $p = static::loadPlugin($value['dirName']); + if (is_object($p)) { + $p->getModeLive($key); + } + self::YPTend("{$value['dirName']}::" . __FUNCTION__); + } + } + + public function getModeLiveLink($liveLink_id) { + $plugins = Plugin::getAllEnabled(); + foreach ($plugins as $value) { + self::YPTstart(); + $p = static::loadPlugin($value['dirName']); + if (is_object($p)) { + $p->getModeLiveLink($liveLink_id); + } + self::YPTend("{$value['dirName']}::" . __FUNCTION__); + } + } public static function getModeYouTubeLive($users_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getModeYouTubeLive($users_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function getEmbed($videos_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getEmbed($videos_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function getChannel($user_id, $user) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->getChannel($user_id, $user); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function getLiveApplicationArray() { $plugins = Plugin::getAllEnabled(); $array = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $appArray = $p->getLiveApplicationArray(); $array = array_merge($array, $appArray); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $array; } public static function getPlayListButtons($playlist_id = "") { if (empty($playlist_id)) return ""; $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getPlayListButtons($playlist_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getMyAccount($users_id = "") { if (empty($users_id)) return ""; $plugins = Plugin::getAllEnabled(); $str = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $str .= $p->getMyAccount($users_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $str; } public static function getPluginUserOptions() { $plugins = Plugin::getAllEnabled(); $userOptions = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $userOptions = array_merge($userOptions, $p->getUserOptions()); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $userOptions; } /** * * @return type return a list of IDs of the user groups */ public static function getDynamicUserGroupsId($users_id) { $plugins = Plugin::getAllEnabled(); $array = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $appArray = $p->getDynamicUserGroupsId($users_id); $array = array_merge($array, $appArray); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $array; } public static function getDynamicUsersId($users_groups_id) { $plugins = Plugin::getAllEnabled(); $array = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $appArray = $p->getDynamicUsersId($users_groups_id); $array = array_merge($array, $appArray); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $array; } public static function getUserOptions() { $userOptions = static::getPluginUserOptions(); $str = ""; foreach ($userOptions as $userOption => $id) { $str .= "
  • " . __($userOption) . "
  • "; } return $str; } public static function addUserBtnJS() { $userOptions = static::getPluginUserOptions(); $userOptions = array(); $js = ""; foreach ($userOptions as $userOption => $id) { $js .= " $('#$id').prop('checked', false);\n"; } return $js; } public static function updateUserFormJS() { $userOptions = static::getPluginUserOptions(); $js = ""; foreach ($userOptions as $userOption => $id) { $js .= " \"$id\": $('#$id').is(':checked'),\n"; } return $js; } public static function loadUsersFormJS() { $userOptions = static::getPluginUserOptions(); $js = ""; foreach ($userOptions as $userOption => $id) { $js .= " $('#$id').prop('checked', (row.$id == \"1\" ? true : false)); \n"; } return $js; } public static function navBarButtons() { $plugins = Plugin::getAllEnabled(); $userOptions = array(); $navBarButtons = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $navBarButtons .= $p->navBarButtons(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $navBarButtons; } public static function navBarProfileButtons() { $plugins = Plugin::getAllEnabled(); $userOptions = array(); $navBarButtons = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $navBarButtons .= $p->navBarProfileButtons(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $navBarButtons; } public static function navBar() { $plugins = Plugin::getAllEnabled(); $userOptions = array(); $navBarButtons = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $navBarButtons .= $p->navBar(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $navBarButtons; } /** * excecute update function at plugin and * update plugin version at database */ public static function updatePlugin($name) { $p = static::loadPlugin($name); if(empty($p)){ return false; } $currentVersion = $p->getPluginVersion(); $uuid = $p->getUUID(); _error_log("AVideoPlugin::updatePlugin name=($name) uuid=($uuid) "); if (method_exists($p, 'updateScript')) { _error_log("AVideoPlugin::updatePlugin method_exists ", AVideoLog::$WARNING); if ($p->updateScript()) Plugin::setCurrentVersionByUuid($uuid, $currentVersion); else return false; } else { _error_log("AVideoPlugin::updatePlugin method NOT exists ", AVideoLog::$WARNING); Plugin::setCurrentVersionByUuid($uuid, $currentVersion); } return true; } public static function getCurrentVersion($name) { $p = static::loadPlugin($name); $uuid = $p->getUUID(); return Plugin::getCurrentVersionByUuid($uuid); } /** * * @param type $name * @param type $version * @return type * -1 if your plugin is lower, * 0 if they are equal, and * 1 if your plugin is greater. */ public static function compareVersion($name, $version) { $currentVersion = self::getCurrentVersion($name); return version_compare($currentVersion, $version); } public static function getSwitchButton($name) { global $global; $p = static::loadPlugin($name); $btn = ""; if (!empty($p)) { $uid = uniqid(); $btn = '
    '; } return $btn; } public static function getAllVideosExcludeVideosIDArray() { $plugins = Plugin::getAllEnabled(); $array = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $array = array_merge($array, $p->getAllVideosExcludeVideosIDArray()); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $array; } public static function userCanUpload($users_id) { if (empty($users_id)) { return false; } $resp = true; $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $can = $p->userCanUpload($users_id); if (!empty($can)) { if ($can < 0) { _error_log("userCanUpload: DENIED The plugin {$value['dirName']} said the user ({$users_id}) can NOT upload a video "); $resp = false; } if ($can > 0) { _error_log("userCanUpload: SUCCESS The plugin {$value['dirName']} said the user ({$users_id}) can upload a video "); return true; } } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $resp; } public static function userCanWatchVideo($users_id, $videos_id) { global $userCanWatchVideoFunction; if(!isset($userCanWatchVideoFunction)){ $userCanWatchVideoFunction = array(); } if(!isset($userCanWatchVideoFunction[$users_id])){ $userCanWatchVideoFunction[$users_id] = array(); } if(isset($userCanWatchVideoFunction[$users_id][$videos_id])){ return $userCanWatchVideoFunction[$users_id][$videos_id]; } $cacheName = "userCanWatchVideo($users_id, $videos_id)"; $cache = ObjectYPT::getSessionCache($cacheName, 600); if(isset($cache)){ return $cache; } $plugins = Plugin::getAllEnabled(); $resp = Video::userGroupAndVideoGroupMatch($users_id, $videos_id); $video = new Video("", "", $videos_id); if (empty($video)) { _error_log("userCanWatchVideo: the usergroup and the video group does not match, User = $users_id, video = $videos_id)"); $userCanWatchVideoFunction[$users_id][$videos_id] = false; ObjectYPT::setSessionCache($cacheName, false); return false; } // check if the video is for paid plans only if ($video->getOnly_for_paid()) { _error_log("userCanWatchVideo: the video ({$videos_id}) is set Only_for_paid = true)"); $resp = false; } foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $can = $p->userCanWatchVideo($users_id, $videos_id); if (!empty($can)) { if ($can < 0) { _error_log("userCanWatchVideo: DENIED The plugin {$value['dirName']} said the user ({$users_id}) can NOT watch the video ({$videos_id})"); $resp = false; } if ($can > 0) { _error_log("userCanWatchVideo: SUCCESS The plugin {$value['dirName']} said the user ({$users_id}) can watch the video ({$videos_id})"); $userCanWatchVideoFunction[$users_id][$videos_id] = true; ObjectYPT::setSessionCache($cacheName, true); return true; } } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } if (!empty($users_id)) { _error_log("userCanWatchVideo: No plugins approve user ({$users_id}) watch the video ({$videos_id}) "); } $userCanWatchVideoFunction[$users_id][$videos_id] = $resp; ObjectYPT::setSessionCache($cacheName, $resp); return $resp; } public static function userCanWatchVideoWithAds($users_id, $videos_id) { global $userCanWatchVideoWithAdsFunction; $users_id = intval($users_id); if(!isset($userCanWatchVideoWithAdsFunction)){ $userCanWatchVideoWithAdsFunction = array(); } if(!isset($userCanWatchVideoWithAdsFunction[$users_id])){ $userCanWatchVideoWithAdsFunction[$users_id] = array(); } if(isset($userCanWatchVideoWithAdsFunction[$users_id][$videos_id])){ return $userCanWatchVideoWithAdsFunction[$users_id][$videos_id]; } $plugins = Plugin::getAllEnabled(); $resp = Video::userGroupAndVideoGroupMatch($users_id, $videos_id); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $can = $p->userCanWatchVideoWithAds($users_id, $videos_id); if (!empty($can)) { $resp = $can > 0 ? true : false; if ($resp) { _error_log("userCanWatchVideoWithAds the plugin ({$value['dirName']}) said user ({$users_id}) can watch"); $userCanWatchVideoWithAdsFunction[$users_id][$videos_id] = true; return true; } else { //_error_log("userCanWatchVideoWithAds: users_id = $users_id, videos_id = $videos_id {$value['dirName']} said no"); } } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } $userCanWatchVideoWithAdsFunction[$users_id][$videos_id] = $resp; return $resp; } public static function showAds($videos_id) { global $_showAds; if(!isset($_showAds)){ $_showAds = array(); } if(isset($_showAds[$videos_id])){ return $_showAds[$videos_id]; } $plugins = Plugin::getAllEnabled(); $resp = true; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $showAds = $p->showAds($videos_id); if (!$showAds) { _error_log("showAds: {$value['dirName']} said NOT to show ads on {$videos_id}"); $_showAds[$videos_id] = false; return false; } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } $_showAds[$videos_id] = $resp; return $resp; } public static function isPaidUser($users_id) { global $_isPaidUser; if(!isset($_isPaidUser)){ $_isPaidUser = array(); } if(isset($_isPaidUser[$users_id])){ return $_isPaidUser[$users_id]; } $plugins = Plugin::getAllEnabled(); $resp = false; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $isPaidUser = $p->isPaidUser($users_id); if ($isPaidUser) { _error_log("isPaidUser: {$value['dirName']} said {$users_id} is a paid user"); $_isPaidUser[$users_id] = true; return true; } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } $_isPaidUser[$users_id] = $resp; return $resp; } /** * In case some plugin needs to play a video that is not allowed for some reason. * A plugin can replace the getVideo method from the youtubeMode page * @return type */ public static function getVideo() { $plugins = Plugin::getAllEnabled(); $resp = null; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $video = $p->getVideo(); if (!empty($video)) { return $video; } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $resp; } public static function onUserSignIn($users_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onUserSignIn($users_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function onUserSignup($users_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onUserSignup($users_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function onLiveStream($users_id, $live_servers_id) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onLiveStream($users_id, $live_servers_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } } public static function onUserSocketConnect() { _mysql_connect(); $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onUserSocketConnect(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } _mysql_close(); } public static function onUserSocketDisconnect() { _mysql_connect(); $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onUserSocketDisconnect(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } _mysql_close(); } public static function thumbsOverlay($videos_id) { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->thumbsOverlay($videos_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function profileTabName($users_id) { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->profileTabName($users_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function profileTabContent($users_id) { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->profileTabContent($users_id); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getVideoTags($videos_id) { global $global, $advancedCustom; if (empty($videos_id) || !empty($global['disableVideoTags']) || !empty($advancedCustom->disableVideoTags)) { return array(); } global $_getVideoTags; if (empty($_getVideoTags)) { $_getVideoTags = array(); } if (isset($_getVideoTags[$videos_id])) { $array = $_getVideoTags[$videos_id]; } else { $name = "getVideoTags{$videos_id}"; $array = ObjectYPT::getCache($name, 86400); //_error_log("getVideoTags $name ".(empty($array)?"new":"old")); if (empty($array)) { TimeLogStart("AVideoPlugin::getVideoTags($videos_id)"); $plugins = Plugin::getAllEnabled(); $array = array(); foreach ($plugins as $value) { $TimeLog = "AVideoPlugin::getVideoTags($videos_id) {$value['dirName']} "; TimeLogStart($TimeLog); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $array = array_merge($array, $p->getVideoTags($videos_id)); } TimeLogEnd($TimeLog, __LINE__); } TimeLogEnd("AVideoPlugin::getVideoTags($videos_id)", __LINE__); ObjectYPT::setCache($name, $array); $_getVideoTags[$videos_id] = $array; } else { //$array = object_to_array($array); } } return $array; } public static function deleteVideoTags($videos_id) { if (empty($videos_id)) { return false; } $name = "getVideoTags{$videos_id}"; _error_log("deleteVideoTags {$name}"); ObjectYPT::deleteSessionCache($name); return ObjectYPT::deleteCache($name); } public static function getVideoWhereClause() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getVideoWhereClause(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getManagerVideosAddNew() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getManagerVideosAddNew(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function saveVideosAddNew($post, $videos_id) { $plugins = Plugin::getAllEnabled(); $r = true; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r = $p->saveVideosAddNew($post, $videos_id) && $r; } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getManagerVideosReset() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getManagerVideosReset(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getManagerVideosEdit() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getManagerVideosEdit(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getManagerVideosEditField() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getManagerVideosEditField(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getManagerVideosJavaScripts() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getManagerVideosJavaScripts(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getManagerVideosTab() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getManagerVideosTab(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getManagerVideosBody() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getManagerVideosBody(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getAllVideosArray($videos_id) { $plugins = Plugin::getAllEnabled(); $r = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r = array_merge($r, $p->getAllVideosArray($videos_id)); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function getUploadMenuButton() { $plugins = Plugin::getAllEnabled(); $r = ""; foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $r .= $p->getUploadMenuButton(); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return $r; } public static function dataSetup() { $plugins = Plugin::getAllEnabled(); $r = array(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $data = $p->dataSetup(); if (!empty($data)) { $r[] = $data; } } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return implode(",", $r); } /* Video properties hooks */ public static function onVideoSetLive_transmitions_history_id($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetLive_transmitions_history_id($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetEncoderURL($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetEncoderURL($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetFilepath($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetFilepath($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetFilesize($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetFilesize($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetUsers_id($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetUsers_id($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetSites_id($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetSites_id($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetVideo_password($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetVideo_password($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetClean_title($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetClean_title($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetDuration($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetDuration($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetIsSuggested($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetIsSuggested($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetStatus($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetStatus($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetType($video_id, $oldValue, $newValue, $force) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetType($video_id, $oldValue, $newValue, $force); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetRotation($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetRotation($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetZoom($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetZoom($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetDescription($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetDescription($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetCategories_id($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetCategories_id($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetVideoDownloadedLink($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetVideoDownloadedLink($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetVideoGroups($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetVideoGroups($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetTrailer1($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetTrailer1($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetTrailer2($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetTrailer2($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetTrailer3($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetTrailer3($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetRate($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetRate($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetYoutubeId($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetYoutubeId($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetTitle($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetTitle($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetFilename($video_id, $oldValue, $newValue, $force) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetFilename($video_id, $oldValue, $newValue, $force); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetNext_videos_id($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetNext_videos_id($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetVideoLink($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetVideoLink($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetCan_download($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetCan_download($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetCan_share($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetCan_share($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetOnly_for_paid($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetOnly_for_paid($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetRrating($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetRrating($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetExternalOptions($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetExternalOptions($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetVideoStartSeconds($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetVideoStartSeconds($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function onVideoSetSerie_playlists_id($video_id, $oldValue, $newValue) { $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { self::YPTstart(); $p = static::loadPlugin($value['dirName']); if (is_object($p)) { $p->onVideoSetSerie_playlists_id($video_id, $oldValue, $newValue); } self::YPTend("{$value['dirName']}::" . __FUNCTION__); } return; } public static function getPluginsOnByDefault($getUUID = true) { if (empty($getUUID)) { return array( 'CustomizeUser', // CustomizeUser 'CustomizeAdvanced', // CustomizeAdvanced 'Layout', // Layout 'PlayerSkins', // PlayerSkins 'Permissions', // Permissions ); } else { return array( '55a4fa56-8a30-48d4-a0fb-8aa6b3fuser3', // CustomizeUser '55a4fa56-8a30-48d4-a0fb-8aa6b3f69033', // CustomizeAdvanced 'layout84-8f5a-4d1b-b912-172c608bf9e3', // Layout 'e9a568e6-ef61-4dcc-aad0-0109e9be8e36', // PlayerSkins 'Permissions-5ee8405eaaa16', // Permissions ); } } public static function getPluginsNameOnByDefaultFromUUID($UUID) { $UUIDs = self::getPluginsOnByDefault(); $key = array_search($UUID, $UUIDs); if($key===false){ return false; } $names = self::getPluginsOnByDefault(false); if (empty($names[$key])) { return false; } return $names[$key]; } public static function isPluginOnByDefault($UUID) { $UUIDs = self::getPluginsOnByDefault(); return in_array($UUID, $UUIDs); } static function fixName($name){ if($name==='Programs'){ return 'PlayLists'; } return $name; } } class YouPHPTubePlugin extends AVideoPlugin { } diff --git a/plugin/BulkEmbed/BulkEmbed.php b/plugin/BulkEmbed/BulkEmbed.php index e54efdc62..b2b4c3325 100644 --- a/plugin/BulkEmbed/BulkEmbed.php +++ b/plugin/BulkEmbed/BulkEmbed.php @@ -1,60 +1,60 @@ Google Developers Console https://console.developers.google.com
    Please ensure that you have enabled the YouTube Data API for your project.'; //$str.= '
    Add the Redirect URI '.$global['webSiteRootURL'].'plugin/BulkEmbed/youtubeSearch.json.php'; $str = 'Create your API Key here https://console.developers.google.com/apis/credentials/key'; $str .= "
    Also make sure you enable the API YouTube Data API v3"; return $str; } public function getName() { return "BulkEmbed"; } public function getUUID() { return "bulkembed-8c31-4f15-a355-48715fac13f3"; } public function getPluginVersion() { return "1.1"; } public function getEmptyDataObject() { global $global; $obj = new stdClass(); $obj->API_KEY = "AIzaSyCIqxE86BawU33Um2HEGtX4PcrUWeCh_6o"; $obj->onlyAdminCanBulkEmbed = true; return $obj; } public function getPluginMenu() { global $global; - $menu = 'Search'; + $menu = ''; return $menu; } public function getUploadMenuButton(){ global $global; $obj = $this->getDataObject(); if(($obj->onlyAdminCanBulkEmbed && !User::isAdmin()) || !User::canUpload()){ return ''; } return '
  • '.__("Bulk Embed").'
  • '; } } diff --git a/plugin/Gallery/functions.php b/plugin/Gallery/functions.php index 75c865353..a8b665694 100644 --- a/plugin/Gallery/functions.php +++ b/plugin/Gallery/functions.php @@ -1,672 +1,672 @@

    " . $info[1] . ""; } else { echo "{$title}"; } ?>

    '; return 0; } $page = $totalPages; $_REQUEST['current'] = $totalPages; } $videos = Video::getAllVideos("viewableNotUnlisted", false, $ignoreGroup); // need to add dechex because some times it return an negative value and make it fails on javascript playlists ?>
    " . __("Up") . ""; $mostLess = $mostWord; } else { if (strpos($orderString, $getName . "=ASC")) { $tmpOrderString = substr($orderString, 0, strpos($orderString, $getName . "=ASC")) . $getName . "=DESC" . substr($orderString, strpos($orderString, $getName . "=ASC") + strlen($getName . "=ASC"), strlen($orderString)); } else { $tmpOrderString .= $getName . "=DESC"; } $upDown = "" . __("Down") . ""; $mostLess = $lessWord; } if (substr($tmpOrderString, strlen($tmpOrderString) - 1, strlen($tmpOrderString)) == "&") { $tmpOrderString = substr($tmpOrderString, 0, strlen($tmpOrderString) - 1); } return array($tmpOrderString, $upDown, $mostLess); } function createGallerySection($videos, $crc = "", $get = array(), $ignoreAds = false, $screenColsLarge = 0, $screenColsMedium = 0, $screenColsSmall = 0, $screenColsXSmall = 0) { global $global, $config, $obj, $advancedCustom, $advancedCustomUser; $countCols = 0; $obj = AVideoPlugin::getObjectData("Gallery"); $zindex = 1000; $startG = microtime(true); $program = AVideoPlugin::loadPluginIfEnabled('PlayLists'); foreach ($videos as $value) { // that meas auto generate the channelName if (empty($get) && !empty($obj->filterUserChannel)) { $getCN = array('channelName' => $value['channelName'], 'catName' => @$_GET['catName']); } else { $getCN = $get; } $img_portrait = (@$value['rotation'] === "90" || @$value['rotation'] === "270") ? "img-portrait" : ""; $name = User::getNameIdentificationById($value['users_id']); $name .= " " . User::getEmailVerifiedIcon($value['users_id']); // make a row each 6 cols if ($countCols % $obj->screenColsLarge === 0) { echo '
    '; } $countCols++; if (!empty($screenColsLarge)) { $obj->screenColsLarge = $screenColsLarge; } if (!empty($screenColsMedium)) { $obj->screenColsMedium = $screenColsMedium; } if (!empty($screenColsSmall)) { $obj->screenColsSmall = $screenColsSmall; } if (!empty($screenColsXSmall)) { $obj->screenColsXSmall = $screenColsXSmall; } $colsClass = "col-lg-" . (12 / $obj->screenColsLarge) . " col-md-" . (12 / $obj->screenColsMedium) . " col-sm-" . (12 / $obj->screenColsSmall) . " col-xs-" . (12 / $obj->screenColsXSmall); $isserie = Video::isSerie($value['id']); $isserieClass = ""; if ($isserie) { $isserieClass = "isserie"; } ?>
    thumbsGif = ""; $images->poster = "" . getCDN() . "view/img/notfound.jpg"; $images->thumbsJpg = "" . getCDN() . "view/img/notfoundThumbs.jpg"; $images->thumbsJpgSmall = "" . getCDN() . "view/img/notfoundThumbsSmall.jpg"; } if ($value['type'] === 'serie' && !empty($value['serie_playlists_id']) && stripos($images->thumbsJpg, 'notfound') !== false) { $images = PlayList::getRandomImageFromPlayList($value['serie_playlists_id']); } $startG = microtime(true); $imgGif = $images->thumbsGif; $poster = $images->thumbsJpg; ?>
    <?php echo $value['title']; ?>" id="thumbsJPG" />


    showCategoryTag)) { $iconClass = 'fas fa-folder'; if (!empty($value['iconClass'])) { $iconClass = $value['iconClass']; } $icon = ''; ?> showTags)) { echo implode('', Video::getTagsHTMLLabelArray($value['id'])); } @$timesG[__LINE__] += microtime(true) - $startG; $startG = microtime(true); ?>
    doNotDisplayViews)) { if (AVideoPlugin::isEnabledByName('LiveUsers')) { echo getLiveUsersLabelVideo($value['id'], $value['views_count'], "", ""); } else { ?>
    Description)) { //$desc = str_replace(array('"', "'", "#", "/", "\\"), array('``', "`", "", "", ""), preg_replace("/\r|\n/", " ", nl2br(trim($value['description'])))); $desc = nl2br(trim($value['description'])); if (!empty($desc)) { $duid = uniqid(); $titleAlert = str_replace(array('"', "'"), array('``', "`"), $value['title']); ?>
    1) { if ($countCols % $obj->screenColsLarge === 0) { echo ""; } if ($countCols % $obj->screenColsMedium === 0) { echo ""; } if ($countCols % $obj->screenColsSmall === 0) { echo ""; } if ($countCols % $obj->screenColsXSmall === 0) { echo ""; } } } ?>
    screenColsLarge === 0) { echo '
    '; } $countCols++; if (!empty($screenColsLarge)) { $obj->screenColsLarge = $screenColsLarge; } if (!empty($screenColsMedium)) { $obj->screenColsMedium = $screenColsMedium; } if (!empty($screenColsSmall)) { $obj->screenColsSmall = $screenColsSmall; } if (!empty($screenColsXSmall)) { $obj->screenColsXSmall = $screenColsXSmall; } $colsClass = "col-lg-" . (12 / $obj->screenColsLarge) . " col-md-" . (12 / $obj->screenColsMedium) . " col-sm-" . (12 / $obj->screenColsSmall) . " col-xs-" . (12 / $obj->screenColsXSmall); if (!empty($video['className'])) { $colsClass .= " {$video['className']}"; } $liveNow = '' . __("LIVE NOW") . ''; ?>
    <?php echo $video['title'] ?>

    showCategoryTag)) { ?>
    Description)) { $desc = str_replace(array('"', "'", "#", "/", "\\"), array('``', "`", "", "", ""), preg_replace("/\r|\n/", " ", nl2br(trim($video['description'])))); if (!empty($desc)) { $titleAlert = str_replace(array('"', "'"), array('``', "`"), $video['title']); ?>
    1) { if ($countCols % $obj->screenColsLarge === 0) { echo ""; } if ($countCols % $obj->screenColsMedium === 0) { echo ""; } if ($countCols % $obj->screenColsSmall === 0) { echo ""; } if ($countCols % $obj->screenColsXSmall === 0) { echo ""; } } } ?>
    $(document).ready(function () {eval("' . $video['galleryCallback'] . '")});'; + echo ''; } unset($_POST['disableAddTo']); return $countCols; } function createChannelItem($users_id, $photoURL = "", $identification = "", $rowCount = 12) { $total = Video::getTotalVideos("viewable", $users_id); if (empty($total)) { return false; } if (empty($photoURL)) { $photoURL = User::getPhoto($users_id); } if (empty($identification)) { $identification = User::getNameIdentificationById($users_id); } ?>

    Channel Owner

    "; return $countCols; } function canPrintCategoryTitle($title) { global $doNotRepeatCategoryTitle; if (!isset($doNotRepeatCategoryTitle)) { $doNotRepeatCategoryTitle = array(); } if (in_array($title, $doNotRepeatCategoryTitle)) { return false; } $doNotRepeatCategoryTitle[] = $title; return true; } ?> diff --git a/plugin/Live/view/menuRight.php b/plugin/Live/view/menuRight.php index 70f8a2b01..9578d18a2 100644 --- a/plugin/Live/view/menuRight.php +++ b/plugin/Live/view/menuRight.php @@ -1,450 +1,452 @@ doNotShowGoLiveButton) && User::canStream()) { ?>
  • " data-placement="bottom" >
  • diff --git a/plugin/LiveLinks/LiveLinks.php b/plugin/LiveLinks/LiveLinks.php index df824c3d5..76a3e5fd4 100644 --- a/plugin/LiveLinks/LiveLinks.php +++ b/plugin/LiveLinks/LiveLinks.php @@ -1,405 +1,464 @@ isReadyLabel(array('Live')); $help = "
    Help"; return $desc . $help; } public function getName() { return "LiveLinks"; } public function getEmptyDataObject() { global $global; $obj = new stdClass(); $obj->onlyAdminCanAddLinks = true; $obj->buttonTitle = "Add a Live Link"; $obj->disableGifThumbs = false; $obj->disableLiveThumbs = false; $obj->doNotShowLiveLinksLabel = false; $obj->disableProxy = false; return $obj; } public function getUUID() { return "39d3b5fe-9702-4f1d-9ffd-fe1cd22a4dc7"; } public function getPluginVersion() { - return "3.2"; + return "4.0"; } public function canAddLinks() { $obj = $this->getDataObject(); if (!User::isLogged()) { return false; } if ($obj->onlyAdminCanAddLinks && !User::isAdmin()) { return false; } return User::canStream(); } public function getHTMLMenuRight() { global $global; $obj = $this->getDataObject(); if (!$this->canAddLinks()) { return ''; } include $global['systemRootPath'] . 'plugin/LiveLinks/view/menuRight.php'; } - static function getAllActive() { + static function getAllActive($future = false, $activeOnly = true, $notStarted = false) { global $global; _mysql_connect(); - $sql = "SELECT * FROM LiveLinks WHERE status='a' AND start_date <= now() AND end_date >= now() ORDER BY start_date "; + $sql = "SELECT * FROM LiveLinks WHERE 1=1 "; + + if (!empty($future)) { + $sql .= " AND end_date >= now() "; + } + + if (!empty($activeOnly)) { + $sql .= " AND status='a' "; + } + + if (!empty($notStarted)) { + $sql .= " AND start_date >= now() "; + } + + $sql .= " ORDER BY start_date "; + //echo $sql;//exit; $res = $global['mysqli']->query($sql); $rows = array(); if ($res) { while ($row = $res->fetch_assoc()) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } static function getImage($id) { global $global; return "{$global['webSiteRootURL']}plugin/LiveLinks/getImage.php?id={$id}&format=jpg"; } static function getImageGif($id) { global $global; return "{$global['webSiteRootURL']}plugin/LiveLinks/getImage.php?id={$id}&format=gif"; } /** * * @return type array(array("key"=>'live key', "users"=>false, "name"=>$userName, "user"=>$user, "photo"=>$photo, "UserPhoto"=>$UserPhoto, "title"=>'')); */ public function getLiveApplicationArray() { global $global; $obj = $this->getDataObject(); $filename = $global['systemRootPath'] . 'plugin/LiveLinks/view/menuItem.html'; $filenameExtra = $global['systemRootPath'] . 'plugin/LiveLinks/view/extraItem.html'; $filenameExtraVideoPage = $global['systemRootPath'] . 'plugin/LiveLinks/view/extraItemVideoPage.html'; $filenameListItem = $global['systemRootPath'] . 'plugin/LiveLinks/view/videoListItem.html'; - $row = LiveLinks::getAllActive(); + $row = LiveLinks::getAllActive(true, true); + //var_dump($row);exit; $array = array(); $search = array( '_unique_id_', '_user_photo_', '_title_', '_user_identification_', '_description_', '_link_', '_imgJPG_', '_imgGIF_', '_class_', '_total_on_live_links_id_' ); $content = file_get_contents($filename); $contentExtra = file_get_contents($filenameExtra); $contentExtraVideoPage = file_get_contents($filenameExtraVideoPage); $contentListem = file_get_contents($filenameListItem); $liveUsers = AVideoPlugin::isEnabledByName('LiveUsers'); foreach ($row as $value) { if ($value['type'] == 'unlisted') { continue; } if ($value['type'] == 'logged_only') { if (!User::isLogged()) { continue; } } $UserPhoto = User::getPhoto($value['users_id']); $name = User::getNameIdentificationById($value['users_id']); $replace = array( $value['id'], $UserPhoto, $value['title'], $name, str_replace('"', "", $value['description']), self::getLink($value['id']), '', empty($obj->disableGifThumbs) ? ('') : "", "col-lg-2 col-md-4 col-sm-4 col-xs-6", ($liveUsers ? getLiveUsersLabelLiveLinks($value['id']) : '') ); $newContent = str_replace($search, $replace, $content); $newContentExtra = str_replace($search, $replace, $contentExtra); $newContentExtraVideoPage = str_replace($search, $replace, $contentExtraVideoPage); $newContentVideoListItem = str_replace($search, $replace, $contentListem); + + $callback = ''; + $galleryCallback = ''; + if(strtotime($value['start_date']) > time()){ + $callback = "liveLinkApps(\$('.liveLink_{$value['id']}'), 'liveLink_{$value['id']}', '{$value['start_date']}')"; + $galleryCallback = 'var liveLinkItemSelector = \'.liveLink_' . $value['id'] . ' .liveNow\'; ' + . '$(liveLinkItemSelector).attr(\'class\', \'liveNow label label-primary\');' + . '$(liveLinkItemSelector).text(\'' . $value['start_date'] . '\');' + . 'startTimerToDate(\'' . $value['start_date'] . '\', liveLinkItemSelector, true);'; + } + $array[] = array( "type" => "LiveLink", "html" => $newContent, "htmlExtra" => $newContentExtra, "htmlExtraVideoPage" => $newContentExtraVideoPage, "htmlExtraVideoListItem" => $newContentVideoListItem, "UserPhoto" => $UserPhoto, "title" => $value['title'], "users_id" => $value['users_id'], "name" => $name, "source" => $value['link'], "poster" => self::getPosterToLiveFromId($value['id']), "imgGif" => self::getPosterToLiveFromId($value['id'], 'gif'), "link" => self::getLinkToLiveFromId($value['id'], true), "href" => self::getLinkToLiveFromId($value['id']), "categories_id" => intval($value['categories_id']), - "className" => 'liveLink_' . $value['id'] + "className" => 'liveLink_' . $value['id'], + "callback" => $callback, + "galleryCallback" => $galleryCallback, ); } return $array; } public function updateScript() { global $global; if (AVideoPlugin::compareVersion($this->getName(), "2") < 0) { $sqls = file_get_contents($global['systemRootPath'] . 'plugin/LiveLinks/install/updateV2.0.sql'); $sqlParts = explode(";", $sqls); foreach ($sqlParts as $value) { sqlDal::writeSql(trim($value)); } } if (AVideoPlugin::compareVersion($this->getName(), "3.1") < 0) { $sqls = file_get_contents($global['systemRootPath'] . 'plugin/LiveLinks/install/updateV3.0.sql'); $sqlParts = explode(";", $sqls); foreach ($sqlParts as $value) { sqlDal::writeSql(trim($value)); } } return true; } public function getHeadCode() { global $global; $obj = $this->getDataObject(); // preload image $js = ""; $css = ''; if (!empty($obj->doNotShowLiveLinksLabel)) { $css .= ''; } return $js . $css; } public static function getLinkToLiveFromId($id, $embed = false) { return self::getLink($id, $embed); } public static function getLink($id, $embed = false) { global $global; //return "{$global['webSiteRootURL']}plugin/LiveLinks/view/Live.php?link={$id}".($embed?"&embed=1":""); $ll = new LiveLinksTable($id); if (!$embed) { return "{$global['webSiteRootURL']}liveLink/{$id}/" . urlencode(cleanURLName($ll->getTitle())); } else { return "{$global['webSiteRootURL']}liveLinkEmbed/{$id}/" . urlencode(cleanURLName($ll->getTitle())); } } public static function getSourceLink($id) { global $global; - if(empty($id)){ + if (empty($id)) { return false; } $ll = new LiveLinksTable($id); - if(empty($ll->getLink())){ + if (empty($ll->getLink())) { return false; } - $liveLink = 'Invalid livelink'.$id; + $liveLink = 'Invalid livelink' . $id; if (filter_var($ll->getLink(), FILTER_VALIDATE_URL)) { $url = parse_url($ll->getLink()); if ($url['scheme'] == 'https') { $liveLink = $ll->getLink(); } else { $liveLink = "{$global['webSiteRootURL']}plugin/LiveLinks/proxy.php?livelink=" . urlencode($ll->getLink()); } } return $liveLink; } public function getPosterToLiveFromId($id, $format = 'jpg') { global $global; return "{$global['webSiteRootURL']}plugin/LiveLinks/getImage.php?id={$id}&format={$format}"; } public static function isLiveThumbsDisabled() { $obj = AVideoPlugin::getDataObject("LiveLinks"); if (!empty($obj->disableLiveThumbs)) { return true; } return false; } public function getPosterThumbsImage($users_id, $live_servers_id) { global $global; $file = Live::_getPosterThumbsImage($users_id, $live_servers_id); if (!file_exists($global['systemRootPath'] . $file)) { $file = "plugin/Live/view/OnAir.jpg"; } return $file; } public function getUploadMenuButton() { global $global; if (!$this->canAddLinks()) { return ''; } $obj = $this->getDataObject(); $buttonTitle = $obj->buttonTitle; //include $global['systemRootPath'] . 'plugin/LiveLinks/getUploadMenuButton.php'; } public static function getAllVideos($status = "", $showOnlyLoggedUserVideos = false, $activeUsersOnly = true) { global $global, $config, $advancedCustom; if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})"); $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__); } } $status = str_replace("'", "", $status); $sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified " . " FROM LiveLinks as v " . " LEFT JOIN categories c ON categories_id = c.id " . " LEFT JOIN users u ON v.users_id = u.id " . " WHERE 1=1 "; if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) { $uid = intval(User::getId()); $sql .= " AND v.users_id = '{$uid}'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $uid = intval($showOnlyLoggedUserVideos); $sql .= " AND v.users_id = '{$uid}'"; } elseif (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $uid = intval($user['id']); $sql .= " AND v.users_id = '{$uid}' "; } if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } if ($status == "publicOnly") { $sql .= " AND v.`type` = 'public' "; } elseif (!empty($status)) { $sql .= " AND v.`status` = '{$status}'"; } if (!empty($_GET['catName'])) { $catName = $global['mysqli']->real_escape_string($_GET['catName']); $sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$catName}' ))"; } if (!empty($_GET['modified'])) { $_GET['modified'] = str_replace("'", "", $_GET['modified']); $sql .= " AND v.modified >= '{$_GET['modified']}'"; } $sql .= AVideoPlugin::getVideoWhereClause(); if (strpos(strtolower($sql), 'limit') === false) { if (!empty($_GET['limitOnceToOne'])) { $sql .= " LIMIT 1"; unset($_GET['limitOnceToOne']); } else { $_REQUEST['rowCount'] = getRowCount(); if (!empty($_REQUEST['rowCount'])) { $sql .= " LIMIT {$_REQUEST['rowCount']}"; } else { _error_log("getAllVideos without limit " . json_encode(debug_backtrace())); if (empty($global['limitForUnlimitedVideos'])) { $global['limitForUnlimitedVideos'] = 100; } if ($global['limitForUnlimitedVideos'] > 0) { $sql .= " LIMIT {$global['limitForUnlimitedVideos']}"; } } } } //echo $sql;exit; //_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $videos = array(); if ($res != false) { foreach ($fullData as $row) { $row = cleanUpRowFromDatabase($row); if (empty($otherInfo)) { $otherInfo = array(); $otherInfo['category'] = xss_esc_back($row['category']); - $otherInfo['groups'] = UserGroups::getVideoGroups($row['id']); + //$otherInfo['groups'] = UserGroups::getVideoGroups($row['id']); //$otherInfo['title'] = UTF8encode($row['title']); $otherInfo['description'] = UTF8encode($row['description']); $otherInfo['descriptionHTML'] = Video::htmlDescription($otherInfo['description']); $otherInfo['filesize'] = 0; } foreach ($otherInfo as $key => $value) { $row[$key] = $value; } $row['rotation'] = 0; $row['filename'] = ''; $row['type'] = 'livelinks'; $row['duration'] = ''; $row['isWatchLater'] = 0; $row['isFavorite'] = 0; $row['views_count'] = 0; $videos[] = $row; } //$videos = $res->fetch_all(MYSQLI_ASSOC); } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $videos; } static function notifySocketToRemoveLiveLinks($liveLinks_id) { $array = array(); $array['stats'] = getStatsNotifications(); $array['autoEvalCodeOnHTML'] = '$(".liveLink_' . $liveLinks_id . '").slideUp();'; $socketObj = sendSocketMessageToAll($array, 'socketRemoveLiveLinks'); return $socketObj; } + public function getFooterCode() { + $obj = $this->getDataObject(); + global $global; + + include $global['systemRootPath'] . 'plugin/LiveLinks/view/footer.php'; + return ''; + } + + static function userCanWatch($users_id, $livelinks_id) { + if(empty($users_id) || empty($livelinks_id)){ + return false; + } + + if(User::isAdmin()){ + return true; + } + + $livelinks = new LiveLinksTable($livelinks_id); + if($livelinks->getUsers_id()==$users_id){ + return true; + } + + $user_groups_ids = LiveLinksTable::getUserGorupsIds($livelinks_id); + if(empty($user_groups_ids)){ + return true; + } + + return LiveLinksTable::userGroupsMatch($livelinks_id, $users_id); + } + } diff --git a/plugin/LiveLinks/Objects/LiveLinksTable.php b/plugin/LiveLinks/Objects/LiveLinksTable.php index 637a758fe..45d73c424 100644 --- a/plugin/LiveLinks/Objects/LiveLinksTable.php +++ b/plugin/LiveLinks/Objects/LiveLinksTable.php @@ -1,166 +1,239 @@ users_id)) { $this->users_id = User::getId(); } if (empty($this->categories_id)) { $this->categories_id = 'NULL'; } Category::clearCacheCount(); $id = parent::save(); if(class_exists('Live') && $id){ Live::deleteStatsCache(true); if($this->status=='a'){ Live::notifySocketStats(); }else{ LiveLinks::notifySocketToRemoveLiveLinks($id); } } return $id; } function getId() { return $this->id; } function getTitle() { return $this->title; } function getDescription() { return $this->description; } function getLink() { return $this->link; } function getStart_date() { return $this->start_date; } function getEnd_date() { return $this->end_date; } function getType() { return $this->type; } function getStatus() { return $this->status; } function getUsers_id() { return $this->users_id; } function setTitle($title) { $this->title = $title; } function setDescription($description) { $this->description = $description; } function setLink($link) { $this->link = $link; } function setStart_date($start_date) { $this->start_date = $start_date; } function setEnd_date($end_date) { $this->end_date = $end_date; } function setType($type) { $this->type = $type; } function setStatus($status) { $this->status = $status; } function setUsers_id($users_id) { $this->users_id = $users_id; } function getCategories_id() { return $this->categories_id; } function setCategories_id($categories_id) { $this->categories_id = intval($categories_id); } public static function getAll($users_id = 0) { global $global; if (!static::isTableInstalled()) { return false; } $users_id = intval($users_id); $sql = "SELECT * FROM " . static::getTableName() . " WHERE 1=1 "; if (!empty($users_id)) { $sql .= " AND users_id = '{$users_id}' "; } $sql .= self::getSqlFromPost(); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { + $row['user_groups'] = self::getUserGorups($row['id']); $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } + public function userGroupsMatch($livelinks_id, $users_id=0){ + $user_groups = self::getUserGorups($livelinks_id); + $user_groups_ids = array(); + foreach ($user_groups as $value) { + $user_groups_ids[] = $value['id']; + } + return User::userGroupsMatch($user_groups_ids, $users_id); + } + public function delete(){ global $global; if(!User::isLogged()){ return false; } if (!empty($this->id)) { $sql = "DELETE FROM " . static::getTableName() . " "; $sql .= " WHERE id = ?"; if (!User::isAdmin()) { $sql .= " AND users_id = ".User::getId(); } $global['lastQuery'] = $sql; //_error_log("Delete Query: ".$sql); return sqlDAL::writeSql($sql, "i", array($this->id)); } _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); return false; } + + public function deleteAllUserGorups(){ + global $global; + if (!empty($this->id)) { + $sql = "DELETE FROM livelinks_has_users_groups "; + $sql .= " WHERE livelinks_id = ?"; + + $global['lastQuery'] = $sql; + //_error_log("Delete Query: ".$sql); + return sqlDAL::writeSql($sql, "i", array($this->id)); + } + _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); + return false; + } + + public function addUserGorups($usergroups_ids){ + global $global; + + if(empty($usergroups_ids)){ + return false; + } + + if(!is_array($usergroups_ids)){ + $usergroups_ids = array($usergroups_ids); + } + foreach ($usergroups_ids as $value) { + $sql = "INSERT INTO `livelinks_has_users_groups` (`livelinks_id`, `users_groups_id`, `created`, `modified`) VALUES (?, ?, now(), now());"; + sqlDAL::writeSql($sql, "ii", array($this->id, $value)); + } + + _error_log("Id for table " . static::getTableName() . " not defined for deletion", AVideoLog::$ERROR); + return true; + } + + + static function getUserGorups($livelinks_id){ + if(!self::isTableInstalled("livelinks_has_users_groups") || empty($livelinks_id)){ + return array(); + } + $sql = "SELECT g.* FROM livelinks_has_users_groups ll LEFT JOIN users_groups g ON users_groups_id = g.id WHERE livelinks_id = ? "; + $sql .= self::getSqlFromPost(); + $res = sqlDAL::readSql($sql, 'i', array($livelinks_id)); + $fullData = sqlDAL::fetchAllAssoc($res); + sqlDAL::close($res); + $rows = array(); + if ($res != false) { + foreach ($fullData as $row) { + $rows[] = $row; + } + } else { + die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); + } + return $rows; + } + + static function getUserGorupsIds($livelinks_id){ + $groups = self::getUserGorups($livelinks_id); + $rows = array(); + foreach ($groups as $value) { + $rows[] = $value['id']; + } + return $rows; + } } diff --git a/plugin/LiveLinks/install/install.sql b/plugin/LiveLinks/install/install.sql index 3fc322dc5..e14c804b5 100644 --- a/plugin/LiveLinks/install/install.sql +++ b/plugin/LiveLinks/install/install.sql @@ -1,43 +1,63 @@ -- MySQL Workbench Synchronization -- Generated: 2017-09-12 22:18 -- Model: New Model -- Version: 1.0 -- Project: Name of the project -- Author: Daniel SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; CREATE TABLE IF NOT EXISTS `LiveLinks` ( `id` INT NOT NULL AUTO_INCREMENT, `title` VARCHAR(255) NOT NULL, `description` TEXT NOT NULL, `link` TEXT NOT NULL, `start_date` DATETIME NULL, `end_date` DATETIME NULL, `type` ENUM('public', 'unlisted', 'logged_only') NULL, `created` DATETIME NULL, `modified` DATETIME NULL, `status` ENUM('a', 'i') NULL DEFAULT 'a', `users_id` INT NOT NULL, `categories_id` INT NULL , PRIMARY KEY (`id`), INDEX `fk_LiveLinks_users_idx` (`users_id` ASC), CONSTRAINT `fk_LiveLinks_users2` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_livelinks_categories1` FOREIGN KEY (`categories_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; +CREATE TABLE IF NOT EXISTS `livelinks_has_users_groups` ( + `id` INT NOT NULL AUTO_INCREMENT, + `livelinks_id` INT(11) NOT NULL, + `users_groups_id` INT(11) NOT NULL, + `created` DATETIME NULL, + `modified` DATETIME NULL, + PRIMARY KEY (`id`), + INDEX `fk_livelinks_has_users_groups_users_groups1_idx` (`users_groups_id` ASC), + INDEX `fk_livelinks_has_users_groups_livelinks1_idx` (`livelinks_id` ASC), + CONSTRAINT `fk_livelinks_has_users_groups_livelinks1` + FOREIGN KEY (`livelinks_id`) + REFERENCES `livelinks` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_livelinks_has_users_groups_users_groups1` + FOREIGN KEY (`users_groups_id`) + REFERENCES `users_groups` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; diff --git a/plugin/LiveLinks/install/updateV4.0.sql b/plugin/LiveLinks/install/updateV4.0.sql new file mode 100644 index 000000000..da87c8c53 --- /dev/null +++ b/plugin/LiveLinks/install/updateV4.0.sql @@ -0,0 +1,20 @@ +CREATE TABLE IF NOT EXISTS `livelinks_has_users_groups` ( + `id` INT NOT NULL AUTO_INCREMENT, + `livelinks_id` INT(11) NOT NULL, + `users_groups_id` INT(11) NOT NULL, + `created` DATETIME NULL, + `modified` DATETIME NULL, + PRIMARY KEY (`id`), + INDEX `fk_livelinks_has_users_groups_users_groups1_idx` (`users_groups_id` ASC), + INDEX `fk_livelinks_has_users_groups_livelinks1_idx` (`livelinks_id` ASC), + CONSTRAINT `fk_livelinks_has_users_groups_livelinks1` + FOREIGN KEY (`livelinks_id`) + REFERENCES `livelinks` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_livelinks_has_users_groups_users_groups1` + FOREIGN KEY (`users_groups_id`) + REFERENCES `users_groups` (`id`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB; \ No newline at end of file diff --git a/plugin/LiveLinks/view/Live.php b/plugin/LiveLinks/view/Live.php index 6479b182b..2b86a2019 100644 --- a/plugin/LiveLinks/view/Live.php +++ b/plugin/LiveLinks/view/Live.php @@ -1,199 +1,208 @@ getId(); if ($liveLink->getType() == 'logged_only' && !User::isLogged()) { die('Link for logged only'); } $uuid = $_GET['link']; $t['id'] = $uuid; $t['users_id'] = $liveLink->getUsers_id(); $t['title'] = $liveLink->getTitle(); $t['link'] = $liveLink->getLink(); $t['description'] = $liveLink->getDescription(); +AVideoPlugin::getModeLiveLink($liveLink->getId()); +$toTime = strtotime($liveLink->getStart_date()); +if ($toTime > time()) { + $message = "{$t['title']}
    {$t['description']}"; + $image = User::getPhoto($t['users_id']); + $bgImage = LiveLinks::getImage($t['id']); + countDownPage($toTime, $message, $image, $bgImage); +} + $u = new User($t['users_id']); $user_id = $u->getBdId(); $subscribe = Subscribe::getButton($user_id); $name = $u->getNameIdentificationBd(); $name = "{$name} " . User::getEmailVerifiedIcon($user_id) . ""; $video = array(); $video['creator'] = '
    User Photo
    ' . $name . '
    ' . $subscribe . '
    '; $video['type'] = "liveLink"; $video['title'] = $t['title']; $video['description'] = $t['description']; $video['users_id'] = $t['users_id']; $poster = $img = LiveLinks::getImage($t['id']); $imgw = 400; $imgh = 255; if (!empty($_GET['embed'])) { $video['videoLink'] = LiveLinks::getSourceLink($t['id']); - include $global['systemRootPath'].'view/videoEmbeded.php'; + include $global['systemRootPath'] . 'view/videoEmbeded.php'; return false; } $isCompressed = AVideoPlugin::loadPluginIfEnabled('TheaterButton') && TheaterButton::isCompressed(); $sideAd = getAdsSideRectangle(); $modeYoutubeBottomClass1 = "col-sm-7 col-md-7 col-lg-6"; $modeYoutubeBottomClass2 = "col-sm-5 col-md-5 col-lg-4 "; if (empty($sideAd) && !AVideoPlugin::loadPluginIfEnabled("Chat2")) { $modeYoutubeBottomClass1 = "col-sm-12 col-md-12 col-lg-10"; $modeYoutubeBottomClass2 = "hidden "; } ?> <?php echo $t['title'] . $config->getPageTitleSeparator() . __("Live Links") . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?> - getWebSiteTitle(); ?>" /> " />

    getChat($uuid); } ?> diff --git a/plugin/LiveLinks/view/addLiveLink.php b/plugin/LiveLinks/view/addLiveLink.php index 90a9c2156..8a89f60b5 100644 --- a/plugin/LiveLinks/view/addLiveLink.php +++ b/plugin/LiveLinks/view/addLiveLink.php @@ -1,30 +1,33 @@ error = true; $obj->msg = ""; $plugin = AVideoPlugin::loadPluginIfEnabled('LiveLinks'); if(!$plugin->canAddLinks()){ $obj->msg = "You cant add links"; die(json_encode($obj)); } $o = new LiveLinksTable(@$_POST['linkId']); $o->setDescription($_POST['description']); $o->setCategories_id($_POST['categories_id']); $o->setEnd_date($_POST['end_date']); $o->setLink($_POST['link']); $o->setStart_date($_POST['start_date']); $o->setStatus($_POST['status']); $o->setTitle($_POST['title']); $o->setType($_POST['type']); -if($o->save()){ +if($id = $o->save()){ + $o = new LiveLinksTable($id); + $o->deleteAllUserGorups(); + $o->addUserGorups($_POST['userGroups']); $obj->error = false; } echo json_encode($obj); diff --git a/plugin/LiveLinks/view/footer.php b/plugin/LiveLinks/view/footer.php new file mode 100644 index 000000000..f4d23a3f3 --- /dev/null +++ b/plugin/LiveLinks/view/footer.php @@ -0,0 +1,18 @@ + \ No newline at end of file diff --git a/plugin/LiveLinks/view/panel.php b/plugin/LiveLinks/view/panel.php index 0824091f1..b0c07d48d 100644 --- a/plugin/LiveLinks/view/panel.php +++ b/plugin/LiveLinks/view/panel.php @@ -1,216 +1,247 @@
    -
    -
    - -
    - - " required="true"> -
    -
    - - -
    -
    - - -
    -
    - - " required > -
    -
    - - " required> -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    -
    - - + +
    + +
    +
    +
    + +
    + + " required="true"> +
    +
    + + +
    +
    + + +
    +
    + + " required > +
    +
    + + " required> +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    +
    +
    +

    +
    + +
    + +
    + /> + +
    +
    + +
    +
    +
    +
    +
    + + +
    -
    +
    - \ No newline at end of file diff --git a/plugin/MaintenanceMode/index.php b/plugin/MaintenanceMode/index.php index 9a5a19457..adda0c49e 100644 --- a/plugin/MaintenanceMode/index.php +++ b/plugin/MaintenanceMode/index.php @@ -1,158 +1,166 @@ + Coming Soon 1 - +
    hideClock) && !empty($obj->endIn)) { ?>
    35 Days
    17 Hours
    50 Minutes
    39 Seconds
    LOGO

    getContactEmail(), $obj->text); ?>

    facebookLink)) { ?> twitterLink)) { ?> googleLink)) { ?> discordLink)) { ?>
    - - + hideClock) && !empty($obj->endIn)) { ?> diff --git a/plugin/MaintenanceMode/vendor/countdowntime/countdowntime.js b/plugin/MaintenanceMode/vendor/countdowntime/countdowntime.js index 42e47accf..b898cba1e 100644 --- a/plugin/MaintenanceMode/vendor/countdowntime/countdowntime.js +++ b/plugin/MaintenanceMode/vendor/countdowntime/countdowntime.js @@ -1,92 +1,93 @@ (function ($) { "use strict"; - $.fn.extend({ - - countdown100: function(options) { - var defaults = { - timeZone: "", - endtimeYear: 0, - endtimeMonth: 0, - endtimeDate: 0, - endtimeHours: 0, - endtimeMinutes: 0, - endtimeSeconds: 0, - } - - var options = $.extend(defaults, options); - - return this.each(function() { - var obj = $(this); - var timeNow = new Date(); - - var tZ = options.timeZone; console.log(tZ); - var endYear = options.endtimeYear; - var endMonth = options.endtimeMonth; - var endDate = options.endtimeDate; - var endHours = options.endtimeHours; - var endMinutes = options.endtimeMinutes; - var endSeconds = options.endtimeSeconds; - - if(tZ == "") { - var deadline = new Date(endYear, endMonth - 1, endDate, endHours, endMinutes, endSeconds); - } - else { - var deadline = moment.tz([endYear, endMonth - 1, endDate, endHours, endMinutes, endSeconds], tZ).format(); - } - - if(Date.parse(deadline) < Date.parse(timeNow)) { - var deadline = new Date(Date.parse(new Date()) + endDate * 24 * 60 * 60 * 1000 + endHours * 60 * 60 * 1000); - } - - - initializeClock(deadline); - - function getTimeRemaining(endtime) { - var t = Date.parse(endtime) - Date.parse(new Date()); - var seconds = Math.floor((t / 1000) % 60); - var minutes = Math.floor((t / 1000 / 60) % 60); - var hours = Math.floor((t / (1000 * 60 * 60)) % 24); - var days = Math.floor(t / (1000 * 60 * 60 * 24)); - return { - 'total': t, - 'days': days, - 'hours': hours, - 'minutes': minutes, - 'seconds': seconds - }; - } - - function initializeClock(endtime) { - var daysSpan = $(obj).find('.days'); - var hoursSpan = $(obj).find('.hours'); - var minutesSpan = $(obj).find('.minutes'); - var secondsSpan = $(obj).find('.seconds'); - - function updateClock() { - var t = getTimeRemaining(endtime); - - daysSpan.html(t.days); - hoursSpan.html(('0' + t.hours).slice(-2)); - minutesSpan.html(('0' + t.minutes).slice(-2)); - secondsSpan.html(('0' + t.seconds).slice(-2)) - - if (t.total <= 0) { - clearInterval(timeinterval); - } + $.fn.extend({ + + countdown100: function (options) { + var defaults = { + timeZone: "", + endtimeYear: 0, + endtimeMonth: 0, + endtimeDate: 0, + endtimeHours: 0, + endtimeMinutes: 0, + endtimeSeconds: 0, } - updateClock(); - var timeinterval = setInterval(updateClock, 1000); - } - - - - - }); - } + var options = $.extend(defaults, options); + + return this.each(function () { + var obj = $(this); + var timeNow = new Date(); + + var tZ = options.timeZone; + console.log(tZ); + var endYear = options.endtimeYear; + var endMonth = options.endtimeMonth; + var endDate = options.endtimeDate; + var endHours = options.endtimeHours; + var endMinutes = options.endtimeMinutes; + var endSeconds = options.endtimeSeconds; + + if (tZ == "") { + var deadline = new Date(endYear, endMonth - 1, endDate, endHours, endMinutes, endSeconds); + } else { + var deadline = moment.tz([endYear, endMonth - 1, endDate, endHours, endMinutes, endSeconds], tZ).format(); + } + + if (Date.parse(deadline) < Date.parse(timeNow)) { + var deadline = new Date(Date.parse(new Date()) + endDate * 24 * 60 * 60 * 1000 + endHours * 60 * 60 * 1000); + } + + + initializeClock(deadline); + + function getTimeRemaining(endtime) { + var t = Date.parse(endtime) - Date.parse(new Date()); + var seconds = Math.floor((t / 1000) % 60); + var minutes = Math.floor((t / 1000 / 60) % 60); + var hours = Math.floor((t / (1000 * 60 * 60)) % 24); + var days = Math.floor(t / (1000 * 60 * 60 * 24)); + return { + 'total': t, + 'days': days, + 'hours': hours, + 'minutes': minutes, + 'seconds': seconds + }; + } + + function initializeClock(endtime) { + var daysSpan = $(obj).find('.days'); + var hoursSpan = $(obj).find('.hours'); + var minutesSpan = $(obj).find('.minutes'); + var secondsSpan = $(obj).find('.seconds'); + + function updateClock() { + var t = getTimeRemaining(endtime); + + daysSpan.html(t.days); + hoursSpan.html(('0' + t.hours).slice(-2)); + minutesSpan.html(('0' + t.minutes).slice(-2)); + secondsSpan.html(('0' + t.seconds).slice(-2)) + + if (t.total <= 0) { + location.reload(); + clearInterval(timeinterval); + } + } + + updateClock(); + var timeinterval = setInterval(updateClock, 1000); + } + + + + + }); + } }); - + })(jQuery); \ No newline at end of file diff --git a/plugin/Meet/Meet.php b/plugin/Meet/Meet.php index 1a330bb35..415a70472 100644 --- a/plugin/Meet/Meet.php +++ b/plugin/Meet/Meet.php @@ -1,570 +1,570 @@ secret = md5($global['systemRootPath'] . $global['salt'] . "meet"); $o = new stdClass(); $o->type = "textarea"; $o->value = "{UserName} is inviting you to a meeting. Topic: {topic} Join Meeting {meetLink} Passcode: {password} "; $obj->invitation = $o; $o = new stdClass(); $o->type = array('ca1.ypt.me' => "North America 1", 'eu1.ypt.me' => "Europe 1", 'custom' => "Custom Jitsi"); $o->value = 'ca1.ypt.me'; $obj->server = $o; $obj->CUSTOM_JITSI_DOMAIN = "jitsi.eu1.ypt.me"; $obj->JWT_APP_ID = "my_jitsi_app_id"; $obj->JWT_APP_SECRET = "my_jitsi_app_secret"; return $obj; } static function getTokenArray($meet_schedule_id, $users_id = 0) { global $config; $obj = AVideoPlugin::getDataObject("Meet"); if (empty($users_id)) { $users_id = User::getId(); } $m = new Meet_schedule($meet_schedule_id); $room = $m->getCleanName(); if (empty($users_id)) { $user = []; } else { $u = new User($users_id); $user = [ "avatar" => $u->getPhotoDB(), "name" => $u->getNameIdentificationBd(), "email" => $u->getEmail(), "id" => $users_id ]; } $jitsiPayload = [ "context" => [ "user" => $user, "group" => $config->getWebSiteTitle() ], "aud" => self::getAUD(), "iss" => self::getISS(), "sub" => "meet.jitsi", "room" => $room, "exp" => strtotime("+30 hours"), "moderator" => self::isModerator($meet_schedule_id) ]; return $jitsiPayload; // HS256 } static function getToken($meet_schedule_id, $users_id = 0) { $m = new Meet_schedule($meet_schedule_id); $jitsiPayload = self::getTokenArray($meet_schedule_id, $users_id); $key = self::getSecret(); //var_dump($jitsiPayload, $key); return JWT::encode($jitsiPayload, $key); // HS256 } static function getSecret() { $obj = AVideoPlugin::getDataObject("Meet"); if ($obj->server->value == 'custom') { if($obj->JWT_APP_SECRET == 'my_jitsi_app_secret'){ return $obj->secret; }else{ return $obj->JWT_APP_SECRET; } } else { return $obj->secret; } } static function getAPPID() { $obj = AVideoPlugin::getDataObject("Meet"); if ($obj->server->value == 'custom') { if($obj->JWT_APP_ID == 'my_jitsi_app_id'){ return "avideo"; }else{ return $obj->JWT_APP_ID; } } else { return "avideo"; } } static function getISS() { $obj = AVideoPlugin::getDataObject("Meet"); if ($obj->server->value == 'custom') { if($obj->JWT_APP_ID == 'my_jitsi_app_id'){ return "*"; }else{ return $obj->JWT_APP_ID; } } else { return "*"; } } static function getAUD() { $obj = AVideoPlugin::getDataObject("Meet"); if ($obj->server->value == 'custom') { if($obj->JWT_APP_ID == 'my_jitsi_app_id'){ return "avideo"; }else{ return $obj->JWT_APP_ID; } } else { return "avideo"; } } static function getMeetServer() { $obj = AVideoPlugin::getDataObject("Meet"); return "https://{$obj->server->value}/"; } public function getPluginMenu() { global $global; //return ' Edit'; - return ' Check Servers'; + return ''; } static function getMeetServerStatus($cache = 30) { global $global; $secret = self::getSecret(); $meetServer = self::getMeetServer(); if ($meetServer == "https://custom/") { $obj = AVideoPlugin::getDataObject("Meet"); $json = new stdClass(); $json->error = false; $json->url = $obj->CUSTOM_JITSI_DOMAIN; $json->isInstalled = true; $json->msg = $obj->CUSTOM_JITSI_DOMAIN; $json->host = "custom"; $json->jibrisInfo = new stdClass(); $json->jibrisInfo->jibris = array(); return $json; } $name = "getMeetServerStatus{$global['webSiteRootURL']}{$secret}{$meetServer}"; $json = new stdClass(); $json->content = ObjectYPT::getCache($name, $cache); if (!empty($json->content) && !empty($json->time)) { $json = _json_decode($json->content); $json->msg = "From Cache"; } else { $url = $meetServer . "api/checkMeet.json.php?webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&secret=" . $secret; $content = url_get_contents($url); $json = _json_decode($content); if (!empty($json)) { $json->time = time(); $json->url = $url; $json->content = $content; if (empty($json->error) && $json->isInstalled) { ObjectYPT::setCache($name, json_encode($json)); if (empty($json->msg)) { $json->msg = "Just create Cache"; } } else { if (empty($json->msg)) { $json->msg = "Error did not create Cache"; } } } else { $json = new stdClass(); $json->time = time(); $json->error = true; $json->msg = "Error we could not check your server"; } } $json->when = humanTimingAgo($json->time); return $json; } static function getDomain() { $json = self::getMeetServerStatus(); if (empty($json) || empty($json->host) || empty($json->isInstalled)) { return false; } if ($json->host == 'custom') { return "custom"; } $obj = AVideoPlugin::getDataObject("Meet"); return "{$json->host}.{$obj->server->value}"; } static function getDomainURL() { $meetDomain = self::getDomain(); if ($meetDomain == 'custom') { $obj = AVideoPlugin::getDataObject("Meet"); $domain = $obj->CUSTOM_JITSI_DOMAIN; } else { $domain = $meetDomain; } return $domain; } static function getJoinURL() { $domain = self::getDomainURL(); $url = "https://" . $domain . "/"; return $url; } static function getRoomID($meet_schedule_id) { $roomName = ""; $m = new Meet_schedule($meet_schedule_id); if (empty($m->getUsers_id())) { return $roomName; } if (!empty($meet_schedule_id)) { $roomName .= $m->getCleanName(); } $token = self::getToken($meet_schedule_id); $roomName .= "?jwt={$token}"; $obj = new stdClass(); if(class_exists("Live")){ $obj->getRTMPLink = Live::getRTMPLink($m->getUsers_id()); } $obj->shareLink = Meet::getMeetShortLink($meet_schedule_id); $roomName .= "&json=" . urlencode(json_encode($obj)); return $roomName; } static function isCustomJitsi() { $json = self::getMeetServerStatus(); if (empty($json) || empty($json->host) || empty($json->isInstalled)) { return true; } if ($json->host == 'custom') { return true; } return false; } static function validateRoomName($room) { return cleanURLName(ucwords($room)); } static function createRoomName($topic, $users_id = 0) { if (empty($users_id)) { if (User::isLogged()) { $identification = User::getNameIdentification(); } } else { $identification = User::getNameIdentificationById($users_id); } if (empty($identification)) { die("User could not be identified"); } $roomName = $identification . "-" . $topic; return self::validateRoomName($roomName); } public function getHTMLMenuRight() { global $global; if (!User::isLogged()) { return ""; } return '
  • '; } public static function getMeetLink($meet_schedule_id) { if (empty($meet_schedule_id)) { return false; } $ms = new Meet_schedule($meet_schedule_id); return $ms->getMeetLink(); } public static function getMeetShortLink($meet_schedule_id) { if (empty($meet_schedule_id)) { return false; } $ms = new Meet_schedule($meet_schedule_id); return $ms->getMeetShortLink(); } static function canManageSchedule($meet_schedule_id) { if (empty($meet_schedule_id)) { return false; } $meet = new Meet_schedule($meet_schedule_id); if ($meet->canManageSchedule()) { return true; } } static function canJoinMeet($meet_schedule_id) { $obj = self::canJoinMeetWithReason($meet_schedule_id); return $obj->canJoin; } static function canJoinMeetWithReason($meet_schedule_id) { $obj = new stdClass(); $obj->canJoin = false; $obj->reason = ""; if (User::isAdmin()) { $obj->canJoin = true; $obj->reason = "Is Admin"; return $obj; } $meet = new Meet_schedule($meet_schedule_id); if (User::getId() == $meet->getUsers_id()) { $obj->canJoin = true; $obj->reason = "Is the meet owner"; return $obj; } /** * Public = 2 * Logged Users Only = 1 * Specific User Groups = 0 * @return type */ if (empty($meet->getStarts()) || strtotime($meet->getStarts()) <= time()) { // means public if ($meet->getPublic() == "2") { $obj->canJoin = true; $obj->reason = "Is public"; return $obj; } else if ($meet->getPublic() == "1") { $obj->canJoin = User::isLogged(); $obj->reason = $obj->canJoin ? "Is logged" : "Must be logged to be able to join"; return $obj; } else { $obj->canJoin = self::userGroupMatch($meet_schedule_id, User::getId()); $obj->reason = $obj->canJoin ? "The user group match" : "Must be on the usergroup to be able to join"; return $obj; } } else { $obj->reason = "The meet does not start yet"; return $obj; } } static function isModerator($meet_schedule_id) { if (empty($meet_schedule_id)) { return false; } if (!User::isLogged()) { return false; } if (User::isAdmin()) { return true; } $meet = new Meet_schedule($meet_schedule_id); if (User::getId() == $meet->getUsers_id()) { return true; } return false; } static function getButtons($meet_schedule_id) { /* return [ 'microphone', 'camera', 'closedcaptions', 'desktop', 'embedmeeting', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'chat', 'recording', 'livestreaming', 'etherpad', 'sharedvideo', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'invite', 'feedback', 'stats', 'shortcuts', 'tileview', 'videobackgroundblur', 'download', 'help', 'mute-everyone', 'security' ]; * */ if (self::isModerator($meet_schedule_id)) { if (self::hasJibris()) { return [ 'microphone', 'camera', 'closedcaptions', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'chat', 'livestreaming', 'etherpad', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'feedback', 'stats', 'shortcuts', 'tileview', 'download', 'help', 'mute-everyone' ]; } else { return [ 'microphone', 'camera', 'closedcaptions', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'chat', 'etherpad', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'feedback', 'stats', 'shortcuts', 'tileview', 'download', 'help', 'mute-everyone' ]; } } else { return [ 'microphone', 'camera', 'closedcaptions', 'desktop', 'fullscreen', 'fodeviceselection', 'hangup', 'profile', 'chat', 'etherpad', 'settings', 'raisehand', 'videoquality', 'filmstrip', 'feedback', 'stats', 'shortcuts', 'tileview', 'download', 'help', 'mute-everyone' ]; } } static function hasJibris() { $serverStatus = Meet::getMeetServerStatus(); return count($serverStatus->jibrisInfo->jibris); } static function userGroupMatch($meet_schedule_id, $users_id) { global $global; if (User::isAdmin()) { return true; } if (User::isLogged()) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; $userGroups = UserGroups::getUserGroups(User::getId()); $meetGroups = Meet_schedule_has_users_groups::getAllFromSchedule($meet_schedule_id); foreach ($userGroups as $value) { foreach ($meetGroups as $value2) { if ($value['id'] == $value2['users_groups_id']) { return true; } } } } return false; } static function getServer() { $m = AVideoPlugin::loadPlugin("Meet"); $pObj = AVideoPlugin::getDataObject("Meet"); $obj = $m->getEmptyDataObject(); $obj->server->type = object_to_array($obj->server->type); return array("name" => $obj->server->type[$pObj->server->value], "domain" => $pObj->server->value); } static function createJitsiButton($title, $svg, $onclick, $class = "", $style = "", $id = "") { global $global; if (empty($id)) { $id = "avideoMeet" . uniqid(); } $svgContent = file_get_contents($global['systemRootPath'] . 'plugin/Meet/buttons/' . $svg); $btn = '
    ' . '' . '
    ' . '
    ' . $svgContent . '
    ' . '
    ' . '
    ' . ''; return $btn; } static function createJitsiRecordStartStopButton($rtmpLink, $dropURL) { $start = self::createJitsiButton(__("Go Live"), "startLive.svg", "aVideoMeetStartRecording('$rtmpLink','$dropURL');", "hideOnLive"); $stop = self::createJitsiButton(__("Stop Live"), "stopLive.svg", "aVideoMeetStopRecording('$rtmpLink','$dropURL');", "showOnLive", "display:none;"); return $start . $stop; } static function getInvitation($meet_schedule_id) { $objM = AVideoPlugin::getObjectDataIfEnabled("Meet"); $ms = new Meet_schedule($meet_schedule_id); $invitation = $objM->invitation->value; $topic = $ms->getTopic(); $pass = $ms->getPassword(); if (empty($topic)) { $invitation = preg_replace("/(\n|\r)[^\n\r]*{topic}[^\n\r]*(\n|\r)/i", "", $invitation); } else { $invitation = preg_replace("/{topic}/i", $topic, $invitation); } if (empty($pass)) { $invitation = preg_replace("/(\n|\r)[^\n\r]*{password}[^\n\r]*(\n|\r)/i", "", $invitation); } else { $invitation = preg_replace("/{password}/i", $pass, $invitation); } $invitation = preg_replace("/{UserName}/i", User::getNameIdentificationById($ms->getUsers_id()), $invitation); $invitation = preg_replace("/{meetLink}/i", $ms->getMeetLink(), $invitation); return $invitation; } static function validatePassword($meet_schedule_id, $password){ if(User::isAdmin() || self::isModerator($meet_schedule_id)){ return true; } $meet = new Meet_schedule($meet_schedule_id); if($meet->getPassword()){ if(empty($_SESSION['user']['meet_password'][$meet_schedule_id])){ if(!empty($password) && $meet->getPassword()==$password){ _session_start(); $_SESSION['user']['meet_password'][$meet_schedule_id] = 1; return true; }else{ return false; } } } return true; } } diff --git a/plugin/MobileManager/upload.php b/plugin/MobileManager/upload.php index 654918954..0136f2a37 100644 --- a/plugin/MobileManager/upload.php +++ b/plugin/MobileManager/upload.php @@ -1,108 +1,108 @@ error = true; $object->videos_id = 0; if (!User::canUpload() && (empty($_GET['user']) || empty($_GET['pass']))) { $object->msg = "You need a user"; die(json_encode($object)); } $user = $_GET['user']; $password = $_GET['pass']; $userObj = new User(0, $user, $password); $userObj->login(false, true); if (!User::canUpload()) { $object->msg = "You can not upload"; die(json_encode($object)); } // A list of permitted file extensions $allowed = array('mp4', 'avi', 'mov', 'mkv', 'flv', 'mp3', 'wav', 'm4v', 'webm', 'wmv', 'mpg', 'mpeg', 'f4v', 'm4v', 'm4a', 'm2p', 'rm', 'vob', 'mkv', 'jpg', 'jpeg', 'gif', 'png', 'webp'); _error_log("MOBILE UPLOAD: Starts"); if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) { $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION); if (!in_array(strtolower($extension), $allowed)) { $object->msg = "File extension error (" . $_FILES['upl']['name'] . "), we allow only (" . implode(",", $allowed) . ")"; _error_log("MOBILE UPLOAD: {$object->msg}"); die(json_encode($object)); } //chack if is an audio $type = "video"; if (strcasecmp($extension, 'mp3') == 0 || strcasecmp($extension, 'wav') == 0) { $type = 'audio'; } require_once $global['systemRootPath'] . 'objects/video.php'; $duration = Video::getDurationFromFile($_FILES['upl']['tmp_name']); // check if can upload video (about time limit storage) if (!empty($global['videoStorageLimitMinutes'])) { $maxDuration = $global['videoStorageLimitMinutes'] * 60; $currentStorageUsage = getSecondsTotalVideosLength(); $thisFile = parseDurationToSeconds($duration); $limitAfterThisFile = $currentStorageUsage + $thisFile; if ($maxDuration < $limitAfterThisFile) { $object->msg = "Sorry, your storage limit has run out." . "
    [Max Duration: {$maxDuration} Seconds]" . "
    [Current Srotage Usage: {$currentStorageUsage} Seconds]" . "
    [This File Duration: {$thisFile} Seconds]" . "
    [Limit after this file: {$limitAfterThisFile} Seconds]"; if (!empty($_FILES['upl']['videoId'])) { $video = new Video("", "", $_FILES['upl']['videoId']); $video->delete(); } _error_log("MOBILE UPLOAD: {$object->msg}"); die(json_encode($object)); } } $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($_FILES['upl']['name'])); $filename = uniqid($mainName . "_YPTuniqid_", true); $video = new Video(preg_replace("/_+/", " ", $_FILES['upl']['name']), $filename, 0); $video->setDuration($duration); if ($type == 'audio') { $video->setType($type); } else { $video->setType("video"); } if(!empty($_REQUEST['title'])){ $video->setTitle($_REQUEST['title']); } if(!empty($_REQUEST['description'])){ $video->setDescription($_REQUEST['description']); } if(!empty($_REQUEST['categories_id'])){ $video->setCategories_id($_REQUEST['categories_id']); } if(!empty($_REQUEST['can_share'])) { $video->setCan_share($_REQUEST['can_share']); } - $video->setStatus('e'); + $video->setStatus(Video::$statusEncoding); if (!move_uploaded_file($_FILES['upl']['tmp_name'], Video::getStoragePath()."original_" . $filename)) { $object->msg = "Error on move_uploaded_file(" . $_FILES['upl']['tmp_name'] . ", " . Video::getStoragePath()."original_" . $filename . ")"; _error_log("MOBILE UPLOAD ERROR: ". json_encode($object)); die(json_encode($object)); } $object->videos_id = $video->save(); $video->queue(); $object->error = false; $object->msg = "We sent your video to the encoder"; _error_log("MOBILE SUCCESS UPLOAD: ". json_encode($object)); die(json_encode($object)); } else { _error_log("MOBILE UPLOAD: File Not exists - " . json_encode($_FILES)); } diff --git a/plugin/Permissions/Permissions.php b/plugin/Permissions/Permissions.php index b26162bbb..b99f25ed7 100644 --- a/plugin/Permissions/Permissions.php +++ b/plugin/Permissions/Permissions.php @@ -1,259 +1,259 @@ Help"; //$desc .= $this->isReadyLabel(array('YPTWallet')); return $desc.$help; } public function getName() { return "Permissions"; } public function getUUID() { return "Permissions-5ee8405eaaa16"; } public function getPluginVersion() { return "1.0"; } public function updateScript() { global $global; /* if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) { sqlDal::executeFile($global['systemRootPath'] . 'plugin/PayPerView/install/updateV2.0.sql'); } * */ return true; } public function getEmptyDataObject() { $obj = new stdClass(); /* $obj->textSample = "text"; $obj->checkboxSample = true; $obj->numberSample = 5; $o = new stdClass(); $o->type = array(0=>__("Default"))+array(1,2,3); $o->value = 0; $obj->selectBoxSample = $o; $o = new stdClass(); $o->type = "textarea"; $o->value = ""; $obj->textareaSample = $o; */ return $obj; } public function getPluginMenu() { global $global; - return ' Edit'; + return ''; } static function getForm() { global $global; $disabled = ""; if (!Users_groups_permissions::isTableInstalled()) { $disabled = " disabled='disabled' "; echo "
    " . " " . __("The Permissions Plugin is not installed. Please install it if you want to customize the permissions.") . "
    "; } $plugins = Plugin::getAllEnabled(); foreach ($plugins as $value) { $row = Plugin::getPluginByName($value['dirName']); $p = AVideoPlugin::loadPlugin($value['dirName']); if (is_object($p) && method_exists($p, 'getPermissionsOptions')) { $array = $p->getPermissionsOptions(); foreach ($array as $value) { if (!is_object($value)) { continue; } echo "
    " . "" . " " . "
    "; } } } return false; } static function hasPermission($type, $pluginName) { global $hasPermission; if (!User::isLogged()) { return false; } if (User::isAdmin()) { return true; } if (empty($hasPermission)) { $hasPermission = array(); } if (empty($hasPermission[$pluginName])) { $hasPermission[$pluginName] = array(); } if (isset($hasPermission[$pluginName][$type])) { return $hasPermission[$pluginName][$type]; } $hasPermission[$pluginName][$type] = false; $groups = UserGroups::getUserGroups(User::getId()); foreach ($groups as $value) { $permissions = Users_groups_permissions::getAllFromUserGorup($value['id']); if (!empty($permissions[$pluginName]) && in_array($type, $permissions[$pluginName])) { $hasPermission[$pluginName][$type] = true; return $hasPermission[$pluginName][$type]; } } return $hasPermission[$pluginName][$type]; } static function canAdminComment() { return self::hasPermission(Permissions::PERMISSION_COMMENTS, 'Permissions'); } static function canAdminVideos() { return self::hasPermission(Permissions::PERMISSION_FULLACCESSVIDEOS, 'Permissions'); } static function canModerateVideos() { return self::hasPermission(Permissions::PERMISSION_INACTIVATEVIDEOS, 'Permissions') || self::canAdminVideos(); } static function canAdminUsers() { return self::hasPermission(Permissions::PERMISSION_USERS, 'Permissions'); } static function canAdminUserGroups() { return self::hasPermission(Permissions::PERMISSION_USERGROUPS, 'Permissions'); } static function canClearCache() { return self::hasPermission(Permissions::PERMISSION_CACHE, 'Permissions'); } static function canGenerateSiteMap() { return self::hasPermission(Permissions::PERMISSION_SITEMAP, 'Permissions'); } static function canSeeLogs() { return self::hasPermission(Permissions::PERMISSION_LOG, 'Permissions'); } /** * const COMMENTS = 1; const FULLACCESSVIDEOS = 10; const INACTIVATEVIDEOS = 11; const USERS = 20; const USERGROUPS = 30; const CACHE = 40; const SITEMAP = 50; const LOG = 60; */ function getPermissionsOptions() { $permissions = array(); $permissions[] = new PluginPermissionOption(Permissions::PERMISSION_COMMENTS, __("Comments Admin"), __("Users with this option will be able to edit and delete comments in any video"), 'Permissions'); $permissions[] = new PluginPermissionOption(Permissions::PERMISSION_FULLACCESSVIDEOS, __("Videos Admin"), __("Just like admin, this user will have permission to edit and delete videos from any user, including videos from admin"), 'Permissions'); $permissions[] = new PluginPermissionOption(Permissions::PERMISSION_INACTIVATEVIDEOS, __("Videos Moderator"), __("This is a level below the (Videos Admin), this type of user can change the video publicity (Active, Inactive, Unlisted)"), 'Permissions'); $permissions[] = new PluginPermissionOption(Permissions::PERMISSION_USERS, __("Users Admin"), __("This type of user can edit users, can add or remove users into user groups, but cannot make them admins"), 'Permissions'); $permissions[] = new PluginPermissionOption(Permissions::PERMISSION_USERGROUPS, __("Users Groups Admin"), __("Can edit and delete user groups"), 'Permissions'); $permissions[] = new PluginPermissionOption(Permissions::PERMISSION_CACHE, __("Cache Manager"), __("This will give the option to can clear cache (Site and first page)"), 'Permissions'); $permissions[] = new PluginPermissionOption(Permissions::PERMISSION_SITEMAP, __("Sitemap"), __("This will give the option to generate SiteMap"), 'Permissions'); $permissions[] = new PluginPermissionOption(Permissions::PERMISSION_LOG, __("Log"), __("This will give the option to see the log file menu"), 'Permissions'); return $permissions; } static function getPluginPermissions($plugins_id) { global $getPluginPermissions; if(empty($getPluginPermissions)){ $getPluginPermissions = array(); } if(isset($getPluginPermissions[$plugins_id])){ return $getPluginPermissions[$plugins_id]; } $plugin = new Plugin($plugins_id); if(empty($plugin)){ $getPluginPermissions[$plugins_id] = array(); return $getPluginPermissions[$plugins_id]; } $p = AVideoPlugin::loadPlugin($plugin->getName()); if(empty($p)){ $getPluginPermissions[$plugins_id] = array(); return $getPluginPermissions[$plugins_id]; } $options = $p->getPermissionsOptions(); if(empty($options)){ $getPluginPermissions[$plugins_id] = array(); return $getPluginPermissions[$plugins_id]; } $permissions = array(); foreach ($options as $key => $value) { $obj = new stdClass(); $obj->name = $options[$key]->getName(); $obj->type = $options[$key]->getType(); $obj->description = $options[$key]->getDescription(); $obj->className = $options[$key]->getClassName(); $obj->groups = Users_groups_permissions::getAllFromPluginAndType($plugins_id, $value->getType()); $permissions[] = $obj; } $getPluginPermissions[$plugins_id] = $permissions; return $getPluginPermissions[$plugins_id]; } static function getPluginPermissionsFromName($pluginName) { $row = Plugin::getPluginByName($pluginName); if(empty($row['id'])){ return array(); } $plugins_id = $row['id']; return self::getPluginPermissions($plugins_id); } static function setPermission($users_groups_id, $plugins_id, $type, $isEnabled) { //var_dump($users_groups_id, $plugins_id, $type, $isEnabled, $_POST); $row = Users_groups_permissions::getFromUserGroupAndPluginAndType($users_groups_id, $plugins_id, $type, false); //var_dump($users_groups_id, $plugins_id, $type, $isEnabled, $row); if(!empty($row['id'])){ $ugp = new Users_groups_permissions($row['id']); }else{ $ugp = new Users_groups_permissions(); $ugp->setusers_groups_id($users_groups_id); $ugp->setPlugins_id($plugins_id); $ugp->setType($type); } $ugp->setStatus($isEnabled?'a':'i'); return $ugp->save(); } } diff --git a/plugin/PlayLists/PlayLists.php b/plugin/PlayLists/PlayLists.php index b9dbc8577..bd7353c44 100644 --- a/plugin/PlayLists/PlayLists.php +++ b/plugin/PlayLists/PlayLists.php @@ -1,758 +1,759 @@ " . " You can use the Edit Parameters button to rename it to your choosing.
    We recommend to keep the Program name " . "as it is defaulted to in order to be well indexed in the SearchTube and Other AVideo Platform search and network indexing tools."; } public function getName() { return "Programs"; } public function getUUID() { return "plist12345-370-4b1f-977a-fd0e5cabtube"; } public function getPluginVersion() { return "1.0"; } public function getEmptyDataObject() { global $global; $obj = new stdClass(); $obj->name = "Program"; $obj->playOnSelect = true; $obj->autoadvance = true; $obj->usersCanOnlyCreatePlayListsFromTheirContent = false; $obj->useOldPlayList = false; $obj->expandPlayListOnChannels = false; $obj->usePlaylistPlayerForSeries = true; $obj->showWatchLaterOnLeftMenu = true; $obj->showFavoriteOnLeftMenu = true; $obj->showWatchLaterOnProfileMenu = true; $obj->showFavoriteOnProfileMenu = true; $obj->showPlayLiveButton = true; $obj->showTrailerInThePlayList = true; $obj->showTVFeatures = false; return $obj; } public function getWatchActionButton($videos_id) { global $global, $livet; if (isLive() && empty($videos_id) && !empty($livet)) { include $global['systemRootPath'] . 'plugin/PlayLists/actionButtonLive.php'; } else { if (!self::canAddVideoOnPlaylist($videos_id)) { return ""; } $obj = $this->getDataObject(); //echo "getNetflixActionButton: ".$videos_id; $btnClass = "btn btn-default no-outline"; include $global['systemRootPath'] . 'plugin/PlayLists/actionButton.php'; } } public function getNetflixActionButton($videos_id) { global $global; if (!self::canAddVideoOnPlaylist($videos_id)) { return ""; } $obj = $this->getDataObject(); //echo "getNetflixActionButton: ".$videos_id; $btnClass = "btn btn-primary"; include $global['systemRootPath'] . 'plugin/PlayLists/actionButton.php'; } public function getGalleryActionButton($videos_id) { global $global; if (!self::canAddVideoOnPlaylist($videos_id)) { return ""; } $obj = $this->getDataObject(); //echo "getNetflixActionButton: ".$videos_id; $btnClass = "text-primary"; echo '
    '; include $global['systemRootPath'] . 'plugin/PlayLists/actionButton.php'; echo '
    '; } public function getHeadCode() { global $global; $obj = $this->getDataObject(); $css = ''; $css .= ''; if(!empty(getPlaylists_id())){ $css .= ""; } return $css; } public function getFooterCode() { global $global; $obj = $this->getDataObject(); include $global['systemRootPath'] . 'plugin/PlayLists/footer.php'; $js = ''; if(isEmbed()){ if(self::showTVFeatures()){ $js .= ''; } } if(isLive() && self::showTVFeatures()){ if(!empty($_REQUEST['playlists_id_live']) && !self::isPlaylistLive($_REQUEST['playlists_id_live']) && self::canManagePlaylist($_REQUEST['playlists_id_live'])){ $liveLink = PlayLists::getLiveLink($_REQUEST['playlists_id_live']); $js .= ''; } } if(!empty(getPlaylists_id())){ PlayerSkins::getStartPlayerJS(file_get_contents("{$global['systemRootPath']}plugin/PlayLists/playerButton.js")); } return $js; } static function canAddVideoOnPlaylist($videos_id) { if (empty($videos_id)) { return false; } $obj = AVideoPlugin::getObjectData("PlayLists"); if (!User::isAdmin() && $obj->usersCanOnlyCreatePlayListsFromTheirContent) { if (User::isLogged()) { $users_id = Video::getOwner($videos_id); if (User::getId() == $users_id) { return true; } } return false; } return true; } static function isVideoOnFavorite($videos_id, $users_id) { return PlayList::isVideoOnFavorite($videos_id, $users_id); } static function isVideoOnWatchLater($videos_id, $users_id) { return PlayList::isVideoOnWatchLater($videos_id, $users_id); } static function getFavoriteIdFromUser($users_id) { return PlayList::getFavoriteIdFromUser($users_id); } static function getWatchLaterIdFromUser($users_id) { return PlayList::getWatchLaterIdFromUser($users_id); } static function getWatchLaterLink() { if (!User::isLogged()) { return ""; } global $global; return "{$global['webSiteRootURL']}watch-later"; } static function getFavoriteLink() { if (!User::isLogged()) { return ""; } global $global; return "{$global['webSiteRootURL']}favorite"; } public function thumbsOverlay($videos_id) { global $global; include $global['systemRootPath'] . 'plugin/PlayLists/buttons.php'; } static function isPlayListASerie($serie_playlists_id) { global $global, $config; $serie_playlists_id = intval($serie_playlists_id); $sql = "SELECT * FROM videos WHERE serie_playlists_id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($serie_playlists_id), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } static function removeSerie($serie_playlists_id) { $video = self::isPlayListASerie($serie_playlists_id); if (!empty($video)) { $video = new Video("", "", $video['id']); return $video->delete(); } return false; } static function saveSerie($serie_playlists_id) { $playlist = new PlayList($serie_playlists_id); if (empty($playlist)) { return false; } $video = self::isPlayListASerie($serie_playlists_id); if (!empty($video)) { $filename = $video['filename']; $v = new Video("", "", $video['id']); } else { $filename = 'serie_playlists_' . uniqid(); $v = new Video("", $filename); } $v->setTitle($playlist->getName()); $v->setSerie_playlists_id($serie_playlists_id); $v->setUsers_id($playlist->getUsers_id()); $v->setStatus('u'); $v->setFilename($filename); $v->setType("serie"); return $v->save(); } public function getStart() { global $global; $whitelistedFiles = array('VMAP.php'); $baseName = basename($_SERVER["SCRIPT_FILENAME"]); if (!in_array($baseName, $whitelistedFiles)) { if (!empty($_GET['videoName'])) { $obj = $this->getDataObject(); if ($obj->usePlaylistPlayerForSeries) { $video = Video::getVideoFromCleanTitle($_GET['videoName']); if ($video['type'] == 'serie' && !empty($video['serie_playlists_id'])) { if (basename($_SERVER["SCRIPT_FILENAME"]) == "videoEmbeded.php") { $link = PlayLists::getLink($video['serie_playlists_id'], true); } else { $link = PlayLists::getLink($video['serie_playlists_id']); } header("Location: {$link}"); exit; } } } } } static function getLink($playlists_id, $embed = false) { global $global; $obj = AVideoPlugin::getObjectData("PlayLists"); if ($embed) { return $global['webSiteRootURL'] . "plugin/PlayLists/embed.php?playlists_id=" . $playlists_id; } else { if (empty($obj->useOldPlayList)) { return $global['webSiteRootURL'] . "plugin/PlayLists/player.php?playlists_id=" . $playlists_id; } else { return $global['webSiteRootURL'] . "program/" . $playlists_id; } } } public function navBarButtons() { global $global; $obj = AVideoPlugin::getObjectData("PlayLists"); $str = ""; if ($obj->showWatchLaterOnLeftMenu) { $str .= '
  • ' . __("Watch Later") . '
  • '; } if ($obj->showFavoriteOnLeftMenu) { $str .= '
  • ' . __("Favorite") . '
  • '; } $str .= '
  • ' . __("Organize") . ' ' .$obj->name . '
  • '; return $str; } public function navBarProfileButtons() { global $global; $obj = AVideoPlugin::getObjectData("PlayLists"); $str = ""; if ($obj->showWatchLaterOnProfileMenu) { $str .= '
  • ' . __("Watch Later") . '
  • '; } if ($obj->showFavoriteOnProfileMenu) { $str .= '
  • ' . __("Favorite") . '
  • '; } return $str; } static function getLiveLink($playlists_id) { global $global; if (!self::canPlayProgramsLive()) { _error_log("PlayLists:getLiveLink canPlayProgramsLive() said no"); return false; } // does it has videos? $videosArrayId = PlayLists::getOnlyVideosAndAudioIDFromPlaylistLight($playlists_id); if (empty($videosArrayId)) { _error_log("PlayLists:getLiveLink getOnlyVideosAndAudioIDFromPlaylistLight($playlists_id) said no"); return false; } return "{$global['webSiteRootURL']}plugin/PlayLists/playProgramsLive.json.php?playlists_id=" . $playlists_id; } static function showPlayLiveButton() { if (!$obj = AVideoPlugin::getDataObjectIfEnabled("PlayLists")) { return false; } return !empty($obj->showPlayLiveButton); } static function canPlayProgramsLive() { // can the user live? if (!User::canStream()) { _error_log("Playlists:canPlayProgramsLive this user cannon stream"); return false; } // Is API enabled if (!AVideoPlugin::isEnabledByName("API")) { _error_log("Playlists:canPlayProgramsLive you need to enable the API plugin to be able to play live programs", AVideoLog::$WARNING); return false; } return true; } static function getOnlyVideosAndAudioIDFromPlaylistLight($playlists_id) { global $global; $sql = "SELECT * FROM playlists_has_videos p " . " LEFT JOIN videos v ON videos_id = v.id " . " WHERE playlists_id = ? AND v.status IN ('" . implode("','", Video::getViewableStatus(true)) . "')" . " AND (`type` = 'video' OR `type` = 'audio' ) ORDER BY p.`order` "; cleanSearchVar(); $sort = @$_POST['sort']; $_POST['sort'] = array(); $_POST['sort']['p.`order`'] = 'ASC'; $_POST['sort'] = $sort; $res = sqlDAL::readSql($sql, "i", array($playlists_id)); $fullData = sqlDAL::fetchAllAssoc($res); reloadSearchVar(); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } static function getLiveEPGLink($playlists_id, $type = 'html') { global $global; $pl = new PlayList($playlists_id); $site = get_domain($global['webSiteRootURL']); $channel = $pl->getUsers_id(); $link = "{$global['webSiteRootURL']}epg.{$type}?site={$site}&channel={$channel}&playlists_id={$playlists_id}"; return $link; } static function getLinkToLive($playlists_id) { global $global; $pl = new PlayList($playlists_id); $link = Live::getLinkToLiveFromUsers_idWithLastServersId($pl->getUsers_id()); return $link . "?playlists_id_live={$playlists_id}"; } static function getImage($playlists_id) { global $global; if(self::isPlaylistLive($playlists_id)){ return self::getLivePosterImage($playlists_id); } $serie = self::isPlayListASerie($playlists_id); if (!empty($serie)) { $tvg_logo = "videos/{$serie['filename']}_tvg.jpg"; $tvg_logo_path = "{$global['systemRootPath']}{$tvg_logo}"; if (!file_exists($tvg_logo_path)) { $images = Video::getSourceFile($serie['filename']); $img = $images["path"]; im_resizeV2($img, $tvg_logo_path, 150, 150, 80); } $tvg_logo_url = "{$global['webSiteRootURL']}{$tvg_logo}"; return $tvg_logo_url; } else { $pl = new PlayList($playlists_id); return User::getPhoto($pl->getUsers_id()); } } static function getLiveImage($playlists_id) { global $global; if(self::isPlaylistLive($playlists_id)){ return self::getLivePosterImage($playlists_id); }else{ return "{$global['webSiteRootURL']}plugin/Live/view/Offline.jpg"; } } static function getNameOrSerieTitle($playlists_id) { $serie = self::isPlayListASerie($playlists_id); if (!empty($serie)) { return $serie['title']; } else { $pl = new PlayList($playlists_id); return $pl->getName(); } } static function getDescriptionIfIsSerie($playlists_id) { $serie = self::isPlayListASerie($playlists_id); if (!empty($serie)) { return $serie['description']; } return ""; } static function getLinkToM3U8($playlists_id, $key, $live_servers_id) { global $global; $_REQUEST['playlists_id_live'] = $playlists_id; $_REQUEST['live_servers_id'] = $live_servers_id; return Live::getM3U8File($key); } static function getM3U8File($playlists_id) { $pl = new PlayList($playlists_id); $users_id = intval($pl->getUsers_id()); $key = self::getPlaylistLiveKey($playlists_id, $users_id); $live_servers_id = self::getPlaylistLiveServersID($playlists_id, $users_id); return self::getLinkToM3U8($playlists_id, $key, $live_servers_id); } static function showTVFeatures() { $obj = AVideoPlugin::getObjectData("PlayLists"); return !empty($obj->showTVFeatures); } static function canManagePlaylist($playlists_id) { if (!User::isLogged()) { return false; } if (User::isAdmin()) { return true; } $pl = new PlayList($playlists_id); if ($pl->getUsers_id() == User::getId()) { return true; } return false; } static function getShowOnTVSwitch($playlists_id) { if (!self::showTVFeatures()) { return ""; } if (!self::canManagePlaylist($playlists_id)) { return ""; } $input = '
    '; return $input; } static function getPlayListEPG($playlists_id, $users_id = 0) { if (empty($users_id)) { $pl = new PlayList($playlists_id); $users_id = ($pl->getUsers_id()); } $epg = self::getUserEPG($users_id); if (empty($epg["playlists"]) || empty($epg["playlists"][$playlists_id])) { return array(); } $epg["playlists"][$playlists_id]['generated'] = $epg['generated']; return $epg["playlists"][$playlists_id]; } static function getUserEPG($users_id) { $epg = self::getSiteEPGs(); if (empty($epg) || empty($epg[$users_id])) { return array(); } $epg[$users_id]['generated'] = $epg['generated']; return $epg[$users_id]; } static function getSiteEPGs($addPlaylistInfo=false) { global $global; $siteDomain = get_domain($global['webSiteRootURL']); $epg = self::getALLEPGs(); if (empty($epg[$siteDomain])) { return array(); } if($addPlaylistInfo){ foreach ($epg[$siteDomain]["channels"] as $key => $value) { foreach ($value['playlists'] as $key2 => $value2) { $pl = new PlayList($value2['playlist_id']); $epg[$siteDomain]["channels"][$key]['playlists'][$key2]['title'] = $pl->getName(); $epg[$siteDomain]["channels"][$key]['playlists'][$key2]['image'] = PlayLists::getImage($value2['playlist_id']); $epg[$siteDomain]["channels"][$key]['playlists'][$key2]['m3u8'] = PlayLists::getLinkToM3U8($value2['playlist_id'], $value2['key'], $value2['live_servers_id']); } } } $epg[$siteDomain]["channels"]['generated'] = $epg['generated']; return $epg[$siteDomain]["channels"]; } static function getALLEPGs() { global $config, $global, $getSiteEPGs; if (!empty($getSiteEPGs)) { return $getSiteEPGs; } $encoder = $config->_getEncoderURL(); $url = "{$encoder}view/videosListEPG.php"; $content = url_get_contents($url); $name = "getALLEPGs_" . md5($url); //$cache = ObjectYPT::getCache($name, 15); //if (!empty($cache)) { // return object_to_array($cache); //} $json = _json_decode($content); if(!is_object($json)){ return array(); } $getSiteEPGs = object_to_array($json->sites); $getSiteEPGs['generated'] = $json->generated; //ObjectYPT::setCache($name, $getSiteEPGs); return $getSiteEPGs; } static function epgFromPlayList($playListArray, $generated, $created, $showClock = false, $linkToLive = false, $showTitle = false) { if (empty($playListArray) || empty($created)) { return ''; } global $global; $uid = uniqid(); $totalDuration = 0; foreach ($playListArray as $value) { $totalDuration += $value['duration_seconds']; } $playlists_id = $playListArray[0]['id']; $current = $generated - $created; $endTime = ($created + $totalDuration); $durationLeft = $endTime - $generated; $percentage_progress = ($current / $totalDuration) * 100; $percentage_left = 100 - floatval($percentage_progress); $epgStep = number_format($percentage_left / $durationLeft, 2); $searchFor = array('{playListname}', '{showClock}', '{linkToLive}', '{totalDuration}', '{created}', '{uid}', '{percentage_progress}', '{epgBars}', '{epgStep}', '{generated}', '{implode}'); $searchForEPGbars = array('{thumbsJpg}', '{represents_percentage}', '{className}', '{epgId}', '{title}', '{text}', '{uid}', '{percentage_progress}'); $epgTemplate = file_get_contents($global['systemRootPath'] . 'plugin/PlayLists/epg.template.html'); $epgBarsTemplate = file_get_contents($global['systemRootPath'] . 'plugin/PlayLists/epg.template.bar.html'); $html = ""; if ($showTitle) { $pl = new PlayList($playlists_id); $playListname = " " . $pl->getName() . ""; } else { $playListname = ""; } if ($showClock) { $showClock = "
    " . getServerClock() . "
    "; } else { $showClock = ""; } if ($linkToLive) { $link = PlayLists::getLinkToLive($playlists_id); $linkToLive = " " . __("Watch Live") . ""; } else { $linkToLive = ""; } $totalDuration_ = secondsToDuration($totalDuration); $created = humanTimingAgo($created); $js = array(); $per = 0; $className = "class_{$uid}"; $epgBars = ""; foreach ($playListArray as $key => $value) { $epgId = "epg_" . uniqid(); $represents_percentage = number_format(($value['duration_seconds'] / $totalDuration) * 100, 2); $images = Video::getImageFromFilename($value['filename']); $per += $represents_percentage; $thumbsJpg = $images->thumbsJpg; if ($per > 100) { $represents_percentage -= $per - 100; } $img = "
    "; $title = addcslashes("{$img} {$value['title']} {$value['duration']}
    {$value['start_date']}", '"'); $text = "{$value['title']}"; $epgBars .= str_replace($searchForEPGbars, array($thumbsJpg, $represents_percentage, $className, $epgId, $title, $text, $uid, $percentage_progress), $epgBarsTemplate); $js[] = " if(currentTime{$uid}>={$value['start']} && currentTime{$uid}<={$value['stop']}){\$('.{$className}').not('#{$epgId}').removeClass('progress-bar-success').addClass('progress-bar-primary');\$('#{$epgId}').addClass('progress-bar-success').removeClass('progress-bar-primary');}"; } $implode = implode("else", $js); return str_replace($searchFor, array($playListname, $showClock, $linkToLive, $totalDuration_, $created, $uid, $percentage_progress, $epgBars, $epgStep, $generated, $implode), $epgTemplate); } static function showOnTV($playlists_id) { if (!self::showTVFeatures()) { return false; } $pl = new PlayList($playlists_id); return !empty($pl->getShowOnTV()); } static function getPlayLiveButton($playlists_id) { if (!self::showPlayLiveButton()) { _error_log("getPlayLiveButton: showPlayLiveButton said no"); return ""; } if (!self::canManagePlaylist($playlists_id)) { _error_log("getPlayLiveButton: canManagePlaylist($playlists_id) said no"); return ""; } global $global; $btnId = "btnId". uniqid(); $label = __("Play Live"); $tooltip = __("Play this Program live now"); $liveLink = PlayLists::getLiveLink($playlists_id); $labelLive = __("Is Live"); $tooltipLive = __("Stop this Program and start over again"); $isLive = "false"; if(self::isPlaylistLive($playlists_id)){ $isLive = "true"; } if (!empty($liveLink)) { $template = file_get_contents("{$global['systemRootPath']}plugin/PlayLists/playLiveButton.html"); return str_replace(array('{isLive}','{liveLink}', '{btnId}', '{label}','{labelLive}', '{tooltip}', '{tooltipLive}'), array($isLive, $liveLink, $btnId, $label, $labelLive, $tooltip, $tooltipLive), $template); }else{ _error_log("getPlayLiveButton: liveLink is empty"); } return ''; } static function getVideosIdFromPlaylist($playlists_id){ return PlayList::getVideosIdFromPlaylist($playlists_id); } static function isPlaylistLive($playlists_id, $users_id = 0){ global $isPlaylistLive; if(!isset($isPlaylistLive)){ $isPlaylistLive = array(); } if(!isset($isPlaylistLive[$playlists_id])){ $json = self::getPlayListEPG($playlists_id, $users_id); $isPlaylistLive[$playlists_id] = !empty($json['isPIDRunning']); } return $isPlaylistLive[$playlists_id]; } static function getPlaylistLiveServersID($playlists_id, $users_id = 0){ $json = self::getPlayListEPG($playlists_id, $users_id); if(!empty($json)){ return intval($json['live_servers_id']); } if (empty($users_id)) { $pl = new PlayList($playlists_id); $users_id = ($pl->getUsers_id()); } $last = LiveTransmitionHistory::getLatestFromUser($users_id); return $last['live_servers_id']; } static function getPlaylistLiveKey($playlists_id, $users_id = 0){ $json = self::getPlayListEPG($playlists_id, $users_id); if(!empty($json['key'])){ return $json['key']; } if (empty($users_id)) { $pl = new PlayList($playlists_id); $users_id = ($pl->getUsers_id()); } $last = LiveTransmitionHistory::getLatestFromUser($users_id); return $last['key']; } public function getLivePosterImage($playlists_id) { $live = AVideoPlugin::loadPluginIfEnabled("Live"); if($live){ $pl = new PlayList($playlists_id); $users_id = intval($pl->getUsers_id()); $live_servers_id = self::getPlaylistLiveServersID($playlists_id, $users_id); return $live->getLivePosterImage($users_id, $live_servers_id)."&playlists_id_live={$playlists_id}"; } return ""; } public function getPluginMenu() { global $global; - return ' Schedule'; + return ''; + //return ' Schedule'; } } diff --git a/plugin/PlayerSkins/PlayerSkins.php b/plugin/PlayerSkins/PlayerSkins.php index d63b26bbe..681f6057a 100644 --- a/plugin/PlayerSkins/PlayerSkins.php +++ b/plugin/PlayerSkins/PlayerSkins.php @@ -1,587 +1,591 @@ The Skis options are: "; $dir = $global['systemRootPath'] . 'plugin/PlayerSkins/skins/'; $names = array(); foreach (glob($dir . '*.css') as $file) { $path_parts = pathinfo($file); $names[] = $path_parts['filename']; } return $desc . "" . implode(" or ", $names) . ""; } public function getName() { return "PlayerSkins"; } public function getUUID() { return "e9a568e6-ef61-4dcc-aad0-0109e9be8e36"; } public function getPluginVersion() { return "1.1"; } public function getEmptyDataObject() { global $global; $obj = new stdClass(); $obj->skin = "avideo"; $obj->playbackRates = "[0.5, 1, 1.5, 2]"; $obj->playerCustomDataSetup = ""; $obj->showSocialShareOnEmbed = true; $obj->showLoopButton = true; $obj->showLogo = false; $obj->showShareSocial = true; $obj->showLogoOnEmbed = false; $obj->showLogoAdjustScale = "0.4"; $obj->showLogoAdjustLeft = "-74px"; $obj->showLogoAdjustTop = "-22px;"; $obj->disableEmbedTopInfo = false; $obj->contextMenuDisableEmbedOnly = false; $obj->contextMenuLoop = true; $obj->contextMenuCopyVideoURL = true; $obj->contextMenuCopyVideoURLCurrentTime = true; $obj->contextMenuCopyEmbedCode = true; $obj->contextMenuShare = true; $obj->playerFullHeight = false; return $obj; } static function getMediaTag($filename, $htmlMediaTag = false) { global $autoPlayURL, $global, $config, $isVideoTypeEmbed; $obj = AVideoPlugin::getObjectData('PlayerSkins'); $html = ''; if (empty($htmlMediaTag)) { $video = Video::getVideoFromFileName($filename, true); $vType = Video::getIncludeType($video); $_GET['isMediaPlaySite'] = $video['id']; if (!empty($video['externalOptions']->videoStartSeconds)) { $video['externalOptions']->videoStartSeconds = parseDurationToSeconds($video['externalOptions']->videoStartSeconds); } else { $video['externalOptions']->videoStartSeconds = 0; } $images = Video::getImageFromFilename($filename); if ($vType == 'video') { $htmlMediaTag = ''; } else if ($vType == 'audio') { $htmlMediaTag = ''; } else if ($vType == 'embed') { $disableYoutubeIntegration = false; if (!empty($advancedCustom->disableYoutubePlayerIntegration)) { $disableYoutubeIntegration = true; } $_GET['isEmbedded'] = ""; if (((strpos($video['videoLink'], "youtu.be") == false) && (strpos($video['videoLink'], "youtube.com") == false) && (strpos($video['videoLink'], "vimeo.com") == false)) || ($disableYoutubeIntegration)) { $_GET['isEmbedded'] = "e"; $isVideoTypeEmbed = 1; $url = parseVideos($video['videoLink']); if ($config->getAutoplay()) { $url = addQueryStringParameter($url, 'autoplay', 1); } $htmlMediaTag = ""; $htmlMediaTag .= ''; $htmlMediaTag .= '
    '; $htmlMediaTag .= ''; $htmlMediaTag .= ''; $htmlMediaTag .= '
    '; } else { // youtube! if ((stripos($video['videoLink'], "youtube.com") != false) || (stripos($video['videoLink'], "youtu.be") != false)) { $_GET['isEmbedded'] = "y"; } else if ((stripos($video['videoLink'], "vimeo.com") != false)) { $_GET['isEmbedded'] = "v"; } $_GET['isMediaPlaySite'] = $video['id']; PlayerSkins::playerJSCodeOnLoad($video['id'], @$video['url']); $htmlMediaTag = ""; $htmlMediaTag .= ''; $htmlMediaTag .= ''; } } else if ($vType == 'serie') { $isVideoTypeEmbed = 1; $link = "{$global['webSiteRootURL']}plugin/PlayLists/embed.php"; $link = addQueryStringParameter($link, 'playlists_id', $video['serie_playlists_id']); $link = addQueryStringParameter($link, 'autoplay', $config->getAutoplay()); $link = addQueryStringParameter($link, 'playlist_index', @$_REQUEST['playlist_index']); $htmlMediaTag = ""; $htmlMediaTag .= ''; $htmlMediaTag .= ''; $htmlMediaTag .= ''; } $html .= "'; } $col1Classes = 'col-md-2 firstC'; $col2Classes = 'col-md-8 secC'; $col3Classes = 'col-md-2 thirdC'; if($obj->playerFullHeight){ $col2Classes .= ' text-center playerFullHeight'; } $html .= '
    ' . $htmlMediaTag . '
    '; if (AVideoPlugin::isEnabledByName('VideoLogoOverlay')) { $style = VideoLogoOverlay::getStyle(); $url = VideoLogoOverlay::getLink(); $html .= ''; } $html .= showCloseButton() . '
    '; return $html; } public function getHeadCode() { global $global, $config, $video; $obj = $this->getDataObject(); $css = ""; $js = ""; if (isLive()) { $js .= ""; } if (isVideo() || !empty($_GET['videoName']) || !empty($_GET['u']) || !empty($_GET['evideo']) || !empty($_GET['playlists_id'])) { if (self::isAutoplayEnabled()) { $js .= ""; } else { $js .= ""; } $js .= ""; if (!empty($obj->skin)) { $css .= "skin}.css\" rel=\"stylesheet\" type=\"text/css\"/>"; } if ($obj->showLoopButton && !isLive()) { $css .= ""; } $css .= ""; $css .= ""; if ($obj->showLogoOnEmbed && isEmbed() || $obj->showLogo) { $logo = "{$global['webSiteRootURL']}" . $config->getLogo(true); $css .= ""; } if ($obj->showShareSocial && CustomizeUser::canShareVideosFromVideo(@$video['id'])) { $css .= ""; } } $url = urlencode(getSelfURI()); $oembed = ''; $oembed .= ''; return $js . $css . $oembed; } public function getFooterCode() { global $global, $config, $getStartPlayerJSWasRequested, $video, $url, $title; $js = ""; $obj = $this->getDataObject(); if (!empty($_GET['videoName']) || !empty($_GET['u']) || !empty($_GET['evideo']) || !empty($_GET['playlists_id'])) { if (empty($obj->showLoopButton) && empty($playerSkinsObj->contextMenuLoop)) { $js .= ""; } if ($obj->showLogoOnEmbed && isEmbed() || $obj->showLogo) { $title = $config->getWebSiteTitle(); $url = "{$global['webSiteRootURL']}{$config->getLogo(true)}"; $js .= ""; PlayerSkins::getStartPlayerJS(file_get_contents("{$global['systemRootPath']}plugin/PlayerSkins/logo.js")); //$js .= ""; } if ($obj->showShareSocial && CustomizeUser::canShareVideosFromVideo(@$video['id'])) { $social = getSocialModal(@$video['id'], @$url, @$title); PlayerSkins::getStartPlayerJS(file_get_contents("{$global['systemRootPath']}plugin/PlayerSkins/shareButton.js")); //$js .= ""; $js .= $social['html']; $js .= ""; } } if (isAudio()) { $videos_id = getVideos_id(); $video = Video::getVideoLight($videos_id); $spectrumSource = Video::getSourceFile($video['filename'], "_spectrum.jpg"); if (!empty($spectrumSource["path"])) { $onPlayerReady = "startAudioSpectrumProgress('{$spectrumSource["url"]}');"; self::prepareStartPlayerJS($onPlayerReady); } } if (!empty($getStartPlayerJSWasRequested) || isVideo()) { $js .= ""; $js .= ""; } return $js; } static function getDataSetup($str = "") { global $video, $disableYoutubeIntegration, $global; $obj = AVideoPlugin::getObjectData('PlayerSkins'); $dataSetup = array(); $dataSetup[] = "errorDisplay: false"; if (!isLive() && !empty($obj->playbackRates)) { $dataSetup[] = "'playbackRates':{$obj->playbackRates}"; } if (!isLive() && (isset($_GET['isEmbedded'])) && ($disableYoutubeIntegration == false) && !empty($video['videoLink'])) { if ($_GET['isEmbedded'] == "y") { $dataSetup[] = "techOrder:[\"youtube\"]"; $dataSetup[] = "sources:[{type: \"video/youtube\", src: \"{$video['videoLink']}\"}]"; $dataSetup[] = "youtube:{customVars: {wmode: \"transparent\", origin: \"{$global['webSiteRootURL']}\"}}"; } else if ($_GET['isEmbedded'] == "v") { $dataSetup[] = "techOrder:[\"vimeo\"]"; $dataSetup[] = "sources:[{type: \"video/vimeo\", src: \"{$video['videoLink']}\"}]"; $dataSetup[] = "vimeo:{customVars: {wmode: \"transparent\", origin: \"{$global['webSiteRootURL']}\"}}"; } } $pluginsDataSetup = AVideoPlugin::dataSetup(); if (!empty($pluginsDataSetup)) { $dataSetup[] = $pluginsDataSetup; } if (!empty($dataSetup)) { return ",{" . implode(",", $dataSetup) . "{$str}{$obj->playerCustomDataSetup}}"; } return ""; } // this function was modified, maybe removed in the future static function getStartPlayerJS($onPlayerReady = "", $getDataSetup = "", $noReadyFunction = false) { global $prepareStartPlayerJS_onPlayerReady, $prepareStartPlayerJS_getDataSetup; global $getStartPlayerJSWasRequested; self::prepareStartPlayerJS($onPlayerReady, $getDataSetup); //var_dump('getStartPlayerJSWasRequested', debug_backtrace()); $getStartPlayerJSWasRequested = true; //return '/* getStartPlayerJS $prepareStartPlayerJS_onPlayerReady = "' . count($prepareStartPlayerJS_onPlayerReady) . '", $prepareStartPlayerJS_getDataSetup = "' . count($prepareStartPlayerJS_getDataSetup) . '", $onPlayerReady = "' . $onPlayerReady . '", $getDataSetup = "' . $getDataSetup . '" */'; return '/* getStartPlayerJS $prepareStartPlayerJS_onPlayerReady = "' . count($prepareStartPlayerJS_onPlayerReady) . '", $prepareStartPlayerJS_getDataSetup = "' . count($prepareStartPlayerJS_getDataSetup) . '" */'; } static function addOnPlayerReady($onPlayerReady){ return self::getStartPlayerJS($onPlayerReady); } static function getStartPlayerJSCode($noReadyFunction = false, $currentTime = 0) { global $config, $global, $prepareStartPlayerJS_onPlayerReady, $prepareStartPlayerJS_getDataSetup, $IMAADTag; $obj = AVideoPlugin::getObjectData('PlayerSkins'); $js = ""; if (empty($currentTime) && !isLive()) { $currentTime = self::getCurrentTime(); } + if(!empty($global['doNotLoadPlayer'])){ + return ''; + } + if(empty($prepareStartPlayerJS_onPlayerReady)){ $prepareStartPlayerJS_onPlayerReady = array(); } if(empty($prepareStartPlayerJS_getDataSetup)){ $prepareStartPlayerJS_getDataSetup = array(); } if (empty($noReadyFunction)) { $js .= "var originalVideo; var adTagOptions; var _adTagUrl = '{$IMAADTag}'; var player; " . "$(document).ready(function () {"; } $js .= " originalVideo = $('#mainVideo').clone(); /* prepareStartPlayerJS_onPlayerReady = " . count($prepareStartPlayerJS_onPlayerReady) . ", prepareStartPlayerJS_getDataSetup = " . count($prepareStartPlayerJS_getDataSetup) . " */ if (typeof player === 'undefined') { player = videojs('mainVideo'" . (self::getDataSetup(implode(" ", $prepareStartPlayerJS_getDataSetup))) . "); "; if (!empty($IMAADTag) && !isLive()) { $js .= "adTagOptions = {id: 'mainVideo', adTagUrl: '{$IMAADTag}', autoPlayAdBreaks:false}; player.ima(adTagOptions);"; $js .= "setInterval(function(){ fixAdSize(); }, 300); // first time it's clicked. var startEvent = 'click';"; if (isMobile()) { $js .= "// Remove controls from the player on iPad to stop native controls from stealing // our click var contentPlayer = document.getElementById('content_video_html5_api'); if (contentPlayer && (navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Android/i)) && contentPlayer.hasAttribute('controls')) { contentPlayer.removeAttribute('controls'); } // Initialize the ad container when the video player is clicked, but only the if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Android/i)) { startEvent = 'touchend'; }"; } $js .= " player.on('adsready', function () { console.log('reloadAds adIsReady '); player.ima.setAdBreakReadyListener(function() {console.log('Ads playAdBreak()');player.ima.playAdBreak();}); });player.on('ads-ad-started', function () { console.log('ads-ad-started'); });player.on('ads-manager', function (a) { console.log('ads-manager', a); });player.on('ads-manager', function (a) { console.log('ads-loader', a); });player.on('ads-manager', function (a) { console.log('ads-request', a); });player.one(startEvent, function () {player.ima.initializeAdDisplayContainer();});"; } $js .= "} player.ready(function () {"; $js .= "var err = this.error(); if (err && err.code) { $('.vjs-error-display').hide(); $('#mainVideo').find('.vjs-poster').css({'background-image': 'url({$global['webSiteRootURL']}plugin/Live/view/Offline.jpg)'}); } " . implode(PHP_EOL, $prepareStartPlayerJS_onPlayerReady) . " playerPlayIfAutoPlay({$currentTime}); }); player.persistvolume({ namespace: 'AVideo' });"; if ($obj->showLoopButton && !isLive()) { $js .= file_get_contents($global['systemRootPath'] . 'plugin/PlayerSkins/loopbutton.js'); } $js .= file_get_contents($global['systemRootPath'] . 'plugin/PlayerSkins/fixCurrentSources.js'); if (empty($noReadyFunction)) { $js .= "});"; } //var_dump('getStartPlayerJSWasRequested', debug_backtrace()); $getStartPlayerJSWasRequested = true; return $js; } static private function getCurrentTime() { global $video; $currentTime = 0; if (isset($_GET['t'])) { $currentTime = intval($_GET['t']); } else if (!empty($video['progress']) && !empty($video['progress']['lastVideoTime'])) { $currentTime = intval($video['progress']['lastVideoTime']); $maxCurrentTime = parseDurationToSeconds($video['duration']); if ($maxCurrentTime <= $currentTime + 5) { if (!empty($video['externalOptions']) && !empty($video['externalOptions']->videoStartSeconds)) { $currentTime = intval($video['externalOptions']->videoStartSeconds); } else { $currentTime = 0; } } } else if (!empty($video['externalOptions']) && !empty($video['externalOptions']->videoStartSeconds)) { $currentTime = intval($video['externalOptions']->videoStartSeconds); } return $currentTime; } static function setIMAADTag($tag) { global $IMAADTag; $IMAADTag = $tag; } static function playerJSCodeOnLoad($videos_id, $nextURL = "") { $js = ""; $videos_id = intval($videos_id); if (empty($videos_id)) { return false; } $video = new Video("", "", $videos_id); if (!empty($video) && empty($nextURL)) { if (!empty($video->getNext_videos_id())) { $next_video = Video::getVideo($video->getNext_videos_id()); if (!empty($next_video['id'])) { $nextURL = Video::getURLFriendly($next_video['id'], isEmbed()); } } else { $catName = @$_GET['catName']; $cat = new Category($video->getCategories_id()); $_GET['catName'] = $cat->getClean_name(); $next_video = Video::getVideo('', 'viewable', false, true); $_GET['catName'] = $catName; if (!empty($next_video['id'])) { $nextURL = Video::getURLFriendly($next_video['id'], isEmbed()); } } } $url = Video::getURLFriendly($videos_id); $js .= " player.on('play', function () { addView({$videos_id}, this.currentTime()); }); player.on('timeupdate', function () { var time = Math.round(this.currentTime()); var url = '{$url}'; if (url.indexOf('?') > -1) { url += '&t=' + time; } else { url += '?t=' + time; } $('#linkCurrentTime, .linkCurrentTime').val(url); if (time >= 5 && time % 30 === 0) { addView({$videos_id}, time); } }); player.on('ended', function () { var time = Math.round(this.currentTime()); addView({$videos_id}, time); });"; if (!empty($nextURL)) { $js .= "playNextURL = '{$nextURL}';"; $js .= "player.on('ended', function () {setTimeout(function(){if(playNextURL){playNext(playNextURL);}},playerHasAds()?10000:500);});"; } self::getStartPlayerJS($js); return true; } static private function prepareStartPlayerJS($onPlayerReady = "", $getDataSetup = "") { global $prepareStartPlayerJS_onPlayerReady, $prepareStartPlayerJS_getDataSetup; if (empty($prepareStartPlayerJS_onPlayerReady)) { $prepareStartPlayerJS_onPlayerReady = array(); } if (empty($prepareStartPlayerJS_getDataSetup)) { $prepareStartPlayerJS_getDataSetup = array(); } if (!empty($onPlayerReady)) { $prepareStartPlayerJS_onPlayerReady[] = $onPlayerReady; } if (!empty($getDataSetup)) { $prepareStartPlayerJS_getDataSetup[] = $getDataSetup; } } static function isAutoplayEnabled() { global $config; if (isLive()) { return true; } if (!empty($_COOKIE['autoplay'])) { if (strtolower($_COOKIE['autoplay']) === 'false') { return false; } else { return true; } } return $config->getAutoplay(); } public static function getVideoTags($videos_id) { if (empty($videos_id)) { return array(); } $name = "PlayeSkins_getVideoTags{$videos_id}"; $tags = ObjectYPT::getCache($name, 0); if (empty($tags)) { //_error_log("Cache not found $name"); $video = new Video("", "", $videos_id); $fileName = $video->getFilename(); $resolution = Video::getHigestResolution($fileName); $obj = new stdClass(); if (empty($resolution) || empty($resolution['resolution_text'])) { $obj->label = ''; $obj->type = ""; $obj->text = ""; } else { $obj->label = 'Plugin'; $obj->type = "danger"; $obj->text = $resolution['resolution_text']; $obj->tooltip = $resolution['resolution'] . 'p'; } $tags = $obj; ObjectYPT::setCache($name, $tags); } return array($tags); } } diff --git a/plugin/Plugin.abstract.php b/plugin/Plugin.abstract.php index 5ef712178..94e74791d 100644 --- a/plugin/Plugin.abstract.php +++ b/plugin/Plugin.abstract.php @@ -1,710 +1,718 @@ getUUID(); if (empty(PluginAbstract::$dataObject[$uuid])) { $obj = Plugin::getPluginByUUID($uuid); //echo $obj['object_data']; $o = array(); if (!empty($obj['object_data'])) { $o = _json_decode(stripslashes($obj['object_data'])); $json_last_error = json_last_error(); if ($json_last_error !== JSON_ERROR_NONE) { //var_dump($this->getName(), $json_last_error, $o, $obj['object_data']); //_error_log('getDataObject - JSON error (' . $json_last_error . ') ' . $this->getName()." ".$this->getUUID()); $o = _json_decode($obj['object_data']); $json_last_error = json_last_error(); } switch ($json_last_error) { case JSON_ERROR_NONE: //echo ' - No errors'; break; default: _error_log('getDataObject - JSON error ' . $this->getName()); _error_log($obj['object_data']); _error_log('striped slashes'); _error_log(stripslashes($obj['object_data'])); case JSON_ERROR_DEPTH: _error_log(' - Maximum stack depth exceeded'); break; case JSON_ERROR_STATE_MISMATCH: _error_log(' - Underflow or the modes mismatch'); break; case JSON_ERROR_CTRL_CHAR: _error_log(' - Unexpected control character found'); break; case JSON_ERROR_SYNTAX: _error_log(' - Syntax error, malformed JSON'); _error_log($obj['object_data']); _error_log('striped slashes'); _error_log(stripslashes($obj['object_data'])); break; case JSON_ERROR_UTF8: _error_log(' - Malformed UTF-8 characters, possibly incorrectly encoded'); break; } } $eo = $this->getEmptyDataObject(); // check if the plugin define any array for the select option, if does, overwrite it foreach ($eo as $key => $value) { if(isset($value->type) && is_array($value->type) && isset($o->$key) && isset($o->$key->type)){ $o->$key->type = $value->type; } } $wholeObjects = array_merge((array) $eo, (array) $o); $disabledPlugins = plugin::getAllDisabled(); foreach ($disabledPlugins as $value) { $p = AVideoPlugin::loadPlugin($value['dirName']); if (is_object($p)) { $foreginObjects = $p->getCustomizeAdvancedOptions(); if ($foreginObjects) { foreach ($foreginObjects as $optionName => $defaultValue) if (isset($wholeObjects[$optionName])) unset($wholeObjects[$optionName]); } } } PluginAbstract::$dataObject[$this->getUUID()] = $wholeObjects; }else { $wholeObjects = PluginAbstract::$dataObject[$this->getUUID()]; } //var_dump($obj['object_data']); //var_dump($eo, $o, (object) array_merge((array) $eo, (array) $o));exit; return (object) $wholeObjects; } public function setDataObject($object) { $pluginRow = Plugin::getPluginByUUID($this->getUUID()); if(empty($pluginRow)){ return false; } $obj = new Plugin($pluginRow['id']); $obj->setObject_data(addcslashes(json_encode($object), '\\')); return $obj->save(); } public function setDataObjectParameter($parameterName, $value) { $object = $this->getDataObject(); eval("\$object->$parameterName = \$value;"); return $this->setDataObject($object); } public function getEmptyDataObject() { $obj = new stdClass(); return $obj; } public function getFirstPage() { return false; } public function afterNewVideo($videos_id) { return false; } public function afterDonation($from_users_id, $how_much, $videos_id, $users_id) { return false; } public function afterNewComment($comments_id) { return false; } public function afterNewResponse($comments_id) { return false; } public function xsendfilePreVideoPlay() { return false; } public function getLogin() { $obj = new stdClass(); $obj->class = ""; // btn btn-primary btn-block $obj->icon = ""; // fab fa-facebook-square $obj->type = ""; // Facebook, Google, etc $obj->linkToDevelopersPage = ""; //https://console.developers.google.com/apis/credentials , https://developers.facebook.com/apps return $obj; } public function getWatchActionButton($videos_id) { return ""; } public function getNetflixActionButton($videos_id) { return ""; } public function getGalleryActionButton($videos_id) { return ""; } public function getStart() { return false; } public function getEnd() { return false; } public function afterVideoJS() { return false; } public function canEditPlugin() { global $global; return empty($global['disableAdvancedConfigurations']); } public function hidePlugin() { return false; } public function getChannelButton() { return ""; } public function getVideoManagerButton() { return ""; } public function getLivePanel() { return ""; } public function getPlayListButtons($playlist_id) { return ""; } public function getMyAccount($users_id) { return ""; } /** * * @return type array(array("key"=>'live key', "users"=>false, "name"=>$userName, "user"=>$user, "photo"=>$photo, "UserPhoto"=>$UserPhoto, "title"=>'')); */ public function getLiveApplicationArray() { return array(); } public function addRoutes() { return false; } public function addView($videos_id, $total) { return false; } public function getCustomizeAdvancedOptions() { return false; } public function getUserOptions() { return array(); } public function getModeYouTube($videos_id) { return false; } + + public function getModeLive($key) { + return false; + } + + public function getModeLiveLink($liveLink_id) { + return false; + } public function getModeYouTubeLive($users_id) { return false; } public function getEmbed($videos_id) { return false; } /** * Loads a channel before display the channel page, usefull to create customized channel pages * @param type $user is an database array from channels owner * @return boolean */ public function getChannel($user_id, $user) { return false; } /** * * @return type return a list of IDs of the user groups */ public function getDynamicUserGroupsId($users_id) { return array(); } public function getDynamicUsersId($users_groups_id) { return array(); } public function navBarButtons() { return ""; } public function navBarProfileButtons() { return ""; } public function navBar() { return ""; } public function isReady($pluginsList) { $return = array('ready' => array(), 'missing' => array()); foreach ($pluginsList as $name) { $plugin = AVideoPlugin::loadPlugin($name); $uuid = $plugin->getUUID(); if (!AVideoPlugin::isEnabled($uuid)) { $return['missing'][] = array('name' => $name, 'uuid' => $uuid); } else { $return['ready'][] = array('name' => $name, 'uuid' => $uuid); } } return $return; } public function isReadyLabel($pluginsList) { $desc = "
    "; $ready = $this->isReady($pluginsList); foreach ($ready['ready'] as $value) { $desc .= "{$value['name']} "; } foreach ($ready['missing'] as $value) { $desc .= "{$value['name']} "; } return $desc; } public function getAllVideosExcludeVideosIDArray() { return array(); } /** * * @param type $users_id * @return 0 = I dont know, -1 = can not upload, 1 = can upload */ public function userCanUpload($users_id) { return 0; } /** * * @param type $users_id * @param type $videos_id * @return 0 = I dont know, -1 = can not watch, 1 = can watch */ public function userCanWatchVideo($users_id, $videos_id) { return 0; } /** * * @param type $users_id * @param type $videos_id * @return 0 = I dont know, -1 = can not watch, 1 = can watch */ public function userCanWatchVideoWithAds($users_id, $videos_id) { return 0; } /** * temporary, to avoid error on old secureVideosDirectory plugins * @return boolean */ function verifyEmbedSecurity() { return true; } function showAds($videos_id) { return true; } function isPaidUser($users_id) { return false; } function getVideo() { return null; } public function onUserSignIn($users_id) { return null; } public function onUserSignup($users_id) { return null; } public function onLiveStream($users_id, $live_servers_id) { return null; } public function thumbsOverlay($videos_id) { return ""; } public static function profileTabName($users_id) { return ""; } public static function profileTabContent($users_id) { return ""; } public static function getVideoWhereClause() { return ""; } public static function getManagerVideosAddNew() { return ""; } public static function saveVideosAddNew($post, $videos_id) { return true; } public static function getManagerVideosReset() { return ""; } public static function getManagerVideosEdit() { return ""; } public static function getManagerVideosEditField() { return ""; } public static function getManagerVideosJavaScripts() { return ""; } public static function getManagerVideosTab() { return ""; } public static function getManagerVideosBody() { return ""; } public static function getAllVideosArray($videos_id) { return array(); } public static function getVideoTags($videos_id) { return array(); } public function getMobileInfo() { return null; } public function getUploadMenuButton() { return ""; } public function dataSetup() { return ""; } function getPermissionsOptions(){ return array(); } protected function addDataObjectHelper($property, $name, $description=""){ $this->dataObjectHelper[$property] = array("name"=>$name, "description"=>$description); } function getDataObjectHelper(){ return $this->dataObjectHelper; } function onUserSocketConnect(){ } function onUserSocketDisconnect(){ } function onVideoSetLive_transmitions_history_id($video_id, $oldValue, $newValue) { } function onVideoSetEncoderURL($video_id, $oldValue, $newValue) { } function onVideoSetFilepath($video_id, $oldValue, $newValue) { } function onVideoSetFilesize($video_id, $oldValue, $newValue) { } function onVideoSetUsers_id($video_id, $oldValue, $newValue) { } function onVideoSetSites_id($video_id, $oldValue, $newValue) { } function onVideoSetVideo_password($video_id, $oldValue, $newValue) { } function onVideoSetClean_title($video_id, $oldValue, $newValue) { } function onVideoSetDuration($video_id, $oldValue, $newValue) { } function onVideoSetIsSuggested($video_id, $oldValue, $newValue) { } function onVideoSetStatus($video_id, $oldValue, $newValue) { } function onVideoSetType($video_id, $oldValue, $newValue, $force) { } function onVideoSetRotation($video_id, $oldValue, $newValue) { } function onVideoSetZoom($video_id, $oldValue, $newValue) { } function onVideoSetDescription($video_id, $oldValue, $newValue) { } function onVideoSetCategories_id($video_id, $oldValue, $newValue) { } function onVideoSetVideoDownloadedLink($video_id, $oldValue, $newValue) { } function onVideoSetVideoGroups($video_id, $oldValue, $newValue) { } function onVideoSetTrailer1($video_id, $oldValue, $newValue) { } function onVideoSetTrailer2($video_id, $oldValue, $newValue) { } function onVideoSetTrailer3($video_id, $oldValue, $newValue) { } function onVideoSetRate($video_id, $oldValue, $newValue) { } function onVideoSetYoutubeId($video_id, $oldValue, $newValue) { } function onVideoSetTitle($video_id, $oldValue, $newValue) { } function onVideoSetFilename($video_id, $oldValue, $newValue, $force) { } function onVideoSetNext_videos_id($video_id, $oldValue, $newValue) { } function onVideoSetVideoLink($video_id, $oldValue, $newValue) { } function onVideoSetCan_download($video_id, $oldValue, $newValue) { } function onVideoSetCan_share($video_id, $oldValue, $newValue) { } function onVideoSetOnly_for_paid($video_id, $oldValue, $newValue) { } function onVideoSetRrating($video_id, $oldValue, $newValue) { } function onVideoSetExternalOptions($video_id, $oldValue, $newValue) { } function onVideoSetVideoStartSeconds($video_id, $oldValue, $newValue) { } function onVideoSetSerie_playlists_id($video_id, $oldValue, $newValue) { } function updateParameter($parameterName, $newValue) { $pluginDO = $this->getDataObject(); $pluginDB = Plugin::getPluginByName($this->getName()); foreach ($pluginDO as $key => $value) { if ($key == $parameterName) { $pluginDO->$key = $newValue; } } $p = new Plugin($pluginDB['id']); $p->setObject_data(json_encode($pluginDO)); return $p->save(); } } class PluginPermissionOption{ private $type, $name, $description, $className; function __construct($type, $name, $description, $className) { $this->type = $type; $this->name = $name; $this->description = $description; $this->className = $className; } function getType() { return $this->type; } function getName() { return $this->name; } function getDescription() { return $this->description; } function getClassName() { return $this->className; } } diff --git a/plugin/TopMenu/pluginMenu.html b/plugin/TopMenu/pluginMenu.html index 36ca1deea..6663c6072 100644 --- a/plugin/TopMenu/pluginMenu.html +++ b/plugin/TopMenu/pluginMenu.html @@ -1 +1 @@ - Create Menus \ No newline at end of file + \ No newline at end of file diff --git a/plugin/VideoTags/pluginMenu.html b/plugin/VideoTags/pluginMenu.html index 261f23477..7207fe350 100644 --- a/plugin/VideoTags/pluginMenu.html +++ b/plugin/VideoTags/pluginMenu.html @@ -1 +1 @@ - Create Tag Type \ No newline at end of file + \ No newline at end of file diff --git a/view/include/head.php b/view/include/head.php index e66186f71..b4f3f0e2b 100644 --- a/view/include/head.php +++ b/view/include/head.php @@ -1,178 +1,183 @@ getDescription(); } if (!empty($poster)) { $subTitle = str_replace(array('"', "\n", "\r"), array("", "", ""), strip_tags($video['description'])); $custom = array(); $custom[] = $subTitle; $custom[] = $video["category"]; } if (!empty($_GET['catName'])) { $category = Category::getCategoryByName($_GET['catName']); $description = str_replace(array('"', "\n", "\r"), array("", "", ""), strip_tags($category['description'])); $custom = array(); $custom[] = $description; $custom[] = $category['name']; } foreach ($custom as $key => $value) { if(empty($value)){ unset($custom[$key]); } } if(!empty($metaDescription)){ $metaDescription = implode(" - ", $custom)." - {$metaDescription}"; }else{ $metaDescription = implode(" - ", $custom); } // for SEO to not rise an error of duplicated title or description of same pages with and without last slash $metaDescription .= getSEOComplement(array("addAutoPrefix" => false)); $theme = getCurrentTheme(); if(empty($config)){ $config = new Configuration(); } ?> keywords)); ?>"> showCustomCSS) && file_exists($filename)){ echo ''; }else{ if($theme !== "default"){ echo ""; } if(empty($customizePlugin->showCustomCSS)){ echo ""; } if(!file_exists($filename)){ echo ""; } echo ''; } $cssFiles = array(); $cssFiles[] = "view/css/main.css"; $cssFiles = array_merge($cssFiles, AVideoPlugin::getCSSFiles()); $cssURL = combineFiles($cssFiles, "css"); ?> getDisable_analytics()) { ?> getHead(); echo $head; if (!empty($video)) { if (!empty($video['users_id'])) { $userAnalytics = new User($video['users_id']); echo $userAnalytics->getAnalytics(); unset($userAnalytics); } } ogSite(); ?> \ No newline at end of file diff --git a/view/mini-upload-form/upload.php b/view/mini-upload-form/upload.php index d845c7692..fd30d37a6 100644 --- a/view/mini-upload-form/upload.php +++ b/view/mini-upload-form/upload.php @@ -1,170 +1,159 @@ error = true; if (!isset($global['systemRootPath'])) { require_once '../../videos/configuration.php'; } if (!User::canUpload()) { $obj->msg = "Only logged users can upload"; die(json_encode($obj)); } header('Content-Type: application/json'); // A list of permitted file extensions $allowed = Video::$types; $advancedCustom = AVideoPlugin::getObjectDataIfEnabled("CustomizeAdvanced"); if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) { $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION); if (!in_array(strtolower($extension), $allowed)) { $obj->msg = "File extension error [{$_FILES['upl']['name']}], we allow only (" . implode(",", $allowed) . ")"; die(json_encode($obj)); } require_once $global['systemRootPath'] . 'objects/video.php'; $duration = Video::getDurationFromFile($_FILES['upl']['tmp_name']); $path_parts = pathinfo($_FILES['upl']['name']); $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($path_parts['filename'])); $filename = uniqid($mainName . "_", true); $videos_id = 0; if (!empty($_FILES['upl']['videoId'])) { $videos_id = $_FILES['upl']['videoId']; } else if (!empty($_POST['videos_id'])) { $videos_id = $_POST['videos_id']; } $title = preg_replace("/_+/", " ", str_ireplace(".{$extension}", "", $_FILES['upl']['name'])); if (empty($videos_id)) { $video = new Video($title, $filename, 0); } else { $video = new Video("", $filename, $videos_id); if ($video->getTitle() === "Video automatically booked") { $video->setTitle($title); - $video->setStatus('i'); + $video->setStatus(Video::$statusInactive); } } //var_dump($videos_id, $_FILES['upl']['name'], $title, $video->getTitle());exit; $video->setDuration($duration); if (!empty($_POST['title'])) { $video->setTitle($_POST['title']); } if (!empty($_POST['description'])) { if (strip_tags($_POST['description']) === $_POST['description']) { $_POST['description'] = nl2br(textToLink($_POST['description'])); } $video->setDescription($_POST['description']); } if ($extension == "mp4" || $extension == "webm") { if (!empty($advancedCustom->disableMP4Upload)) { $obj->msg = "Video Files are not Allowed"; die(json_encode($obj)); } $video->setType("video", true); } else if (($extension == "mp3") || ($extension == "ogg")) { if (!empty($advancedCustom->disableMP3Upload)) { $obj->msg = "MP3 Files are not Allowed"; die(json_encode($obj)); } $video->setType("audio", true); } else if (($extension == "pdf")) { if (!empty($advancedCustom->disablePDFUpload)) { $obj->msg = "PDF Files are not Allowed"; die(json_encode($obj)); } $video->setType("pdf", true); } if (($extension == "jpg" || $extension == "jpeg" || $extension == "png" || $extension == "gif" || $extension == "webp")) { if (!empty($advancedCustom->disableImageUpload)) { $obj->msg = "Images Files are not Allowed"; die(json_encode($obj)); } $video->setType("image", true); } if (($extension == "zip")) { if (!empty($global['disableAdvancedConfigurations'])) { $obj->msg = "Zip is disabled on this server"; die(json_encode($obj)); } if (!empty($advancedCustom->disableZipUpload)) { $obj->msg = "Zip Files are not Allowed"; die(json_encode($obj)); } $video->setType("zip", true); } - if (empty($advancedCustom->makeVideosInactiveAfterEncode) && $video->getTitle() !== "Video automatically booked") { - - // set active - - $video->setStatus('a'); - } else if (empty($advancedCustom->makeVideosUnlistedAfterEncode) && $video->getTitle() !== "Video automatically booked") { - - // set active - - $video->setStatus('u'); - } else { - $video->setStatus('i'); - } + + $video->setAutoStatus(Video::$statusInactive); $id = $video->save(); if ($id) { /** * This is when is using in a non uploaded movie */ $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $tmp_name = $_FILES['upl']['tmp_name']; $filenameMP4 = $filename . "." . $extension; decideMoveUploadedToVideos($tmp_name, $filenameMP4, $video->getType()); if ((AVideoPlugin::isEnabledByName('MP4ThumbsAndGif')) && ($extension == "mp4" || $extension == "webm" || $extension == "mp3")) { $videoFileName = $video->getFilename(); MP4ThumbsAndGif::getImage($videoFileName, 'jpg', $id); MP4ThumbsAndGif::getImage($videoFileName, 'gif', $id); MP4ThumbsAndGif::getImage($videoFileName, 'webp', $id); } // } else if(($extension=="mp3")||($extension=="ogg")){ // } $obj->title = $video->getTitle(); $obj->error = false; $obj->filename = $filename; $obj->duration = $duration; $obj->videos_id = $id; if (!empty($_FILES['upl']['tmp_name'])) { AVideoPlugin::afterNewVideo($obj->videos_id); } if ($extension !== "jpg" && $video->getType() == "image") { sleep(1); // to make sure the file will be available $file = Video::getStoragePath() . "" . $video->getFilename(); try { convertImage("{$file}.{$extension}", "{$file}.jpg", 70); } catch (Exception $exc) { _error_log("We could not convert the image to JPG " . $exc->getMessage()); } } die(json_encode($obj)); } } $obj->msg = "\$_FILES Error"; $obj->FILES = $_FILES; die(json_encode($obj));